github.com/eun/go@v0.0.0-20170811110501-92cfd07a6cfd/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 "fmt" 10 "go/format" 11 "internal/race" 12 "internal/testenv" 13 "io" 14 "io/ioutil" 15 "os" 16 "os/exec" 17 "path/filepath" 18 "regexp" 19 "runtime" 20 "strconv" 21 "strings" 22 "testing" 23 "time" 24 ) 25 26 var ( 27 canRun = true // whether we can run go or ./testgo 28 canRace = false // whether we can run the race detector 29 canCgo = false // whether we can use cgo 30 31 exeSuffix string // ".exe" on Windows 32 33 skipExternal = false // skip external tests 34 ) 35 36 func init() { 37 switch runtime.GOOS { 38 case "android", "nacl": 39 canRun = false 40 case "darwin": 41 switch runtime.GOARCH { 42 case "arm", "arm64": 43 canRun = false 44 } 45 case "linux": 46 switch runtime.GOARCH { 47 case "arm": 48 // many linux/arm machines are too slow to run 49 // the full set of external tests. 50 skipExternal = true 51 case "mips", "mipsle", "mips64", "mips64le": 52 // Also slow. 53 skipExternal = true 54 if testenv.Builder() != "" { 55 // On the builders, skip the cmd/go 56 // tests. They're too slow and already 57 // covered by other ports. There's 58 // nothing os/arch specific in the 59 // tests. 60 canRun = false 61 } 62 } 63 case "freebsd": 64 switch runtime.GOARCH { 65 case "arm": 66 // many freebsd/arm machines are too slow to run 67 // the full set of external tests. 68 skipExternal = true 69 canRun = false 70 } 71 case "windows": 72 exeSuffix = ".exe" 73 } 74 } 75 76 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary 77 // build from this process's current GOROOT, but run from a different 78 // (temp) directory. 79 var testGOROOT string 80 81 var testCC string 82 83 // The TestMain function creates a go command for testing purposes and 84 // deletes it after the tests have been run. 85 func TestMain(m *testing.M) { 86 if canRun { 87 args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix} 88 if race.Enabled { 89 args = append(args, "-race") 90 } 91 out, err := exec.Command("go", args...).CombinedOutput() 92 if err != nil { 93 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out) 94 os.Exit(2) 95 } 96 97 out, err = exec.Command("go", "env", "GOROOT").CombinedOutput() 98 if err != nil { 99 fmt.Fprintf(os.Stderr, "could not find testing GOROOT: %v\n%s", err, out) 100 os.Exit(2) 101 } 102 testGOROOT = strings.TrimSpace(string(out)) 103 104 out, err = exec.Command("go", "env", "CC").CombinedOutput() 105 if err != nil { 106 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out) 107 os.Exit(2) 108 } 109 testCC = strings.TrimSpace(string(out)) 110 111 if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil { 112 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err) 113 canRun = false 114 } else { 115 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out))) 116 if err != nil { 117 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out))) 118 } 119 } 120 121 switch runtime.GOOS { 122 case "linux", "darwin", "freebsd", "windows": 123 // The race detector doesn't work on Alpine Linux: 124 // golang.org/issue/14481 125 canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux() 126 } 127 } 128 129 // Don't let these environment variables confuse the test. 130 os.Unsetenv("GOBIN") 131 os.Unsetenv("GOPATH") 132 os.Unsetenv("GIT_ALLOW_PROTOCOL") 133 if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" { 134 // On some systems the default C compiler is ccache. 135 // Setting HOME to a non-existent directory will break 136 // those systems. Set CCACHE_DIR to cope. Issue 17668. 137 os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache")) 138 } 139 os.Setenv("HOME", "/test-go-home-does-not-exist") 140 141 r := m.Run() 142 143 if canRun { 144 os.Remove("testgo" + exeSuffix) 145 } 146 147 os.Exit(r) 148 } 149 150 func isAlpineLinux() bool { 151 if runtime.GOOS != "linux" { 152 return false 153 } 154 fi, err := os.Lstat("/etc/alpine-release") 155 return err == nil && fi.Mode().IsRegular() 156 } 157 158 // The length of an mtime tick on this system. This is an estimate of 159 // how long we need to sleep to ensure that the mtime of two files is 160 // different. 161 // We used to try to be clever but that didn't always work (see golang.org/issue/12205). 162 var mtimeTick time.Duration = 1 * time.Second 163 164 // Manage a single run of the testgo binary. 165 type testgoData struct { 166 t *testing.T 167 temps []string 168 wd string 169 env []string 170 tempdir string 171 ran bool 172 inParallel bool 173 stdout, stderr bytes.Buffer 174 } 175 176 // testgo sets up for a test that runs testgo. 177 func testgo(t *testing.T) *testgoData { 178 testenv.MustHaveGoBuild(t) 179 180 if skipExternal { 181 t.Skip("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH) 182 } 183 184 return &testgoData{t: t} 185 } 186 187 // must gives a fatal error if err is not nil. 188 func (tg *testgoData) must(err error) { 189 if err != nil { 190 tg.t.Fatal(err) 191 } 192 } 193 194 // check gives a test non-fatal error if err is not nil. 195 func (tg *testgoData) check(err error) { 196 if err != nil { 197 tg.t.Error(err) 198 } 199 } 200 201 // parallel runs the test in parallel by calling t.Parallel. 202 func (tg *testgoData) parallel() { 203 if tg.ran { 204 tg.t.Fatal("internal testsuite error: call to parallel after run") 205 } 206 if tg.wd != "" { 207 tg.t.Fatal("internal testsuite error: call to parallel after cd") 208 } 209 for _, e := range tg.env { 210 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") { 211 val := e[strings.Index(e, "=")+1:] 212 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") { 213 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e) 214 } 215 } 216 } 217 tg.inParallel = true 218 tg.t.Parallel() 219 } 220 221 // pwd returns the current directory. 222 func (tg *testgoData) pwd() string { 223 wd, err := os.Getwd() 224 if err != nil { 225 tg.t.Fatalf("could not get working directory: %v", err) 226 } 227 return wd 228 } 229 230 // cd changes the current directory to the named directory. Note that 231 // using this means that the test must not be run in parallel with any 232 // other tests. 233 func (tg *testgoData) cd(dir string) { 234 if tg.inParallel { 235 tg.t.Fatal("internal testsuite error: changing directory when running in parallel") 236 } 237 if tg.wd == "" { 238 tg.wd = tg.pwd() 239 } 240 abs, err := filepath.Abs(dir) 241 tg.must(os.Chdir(dir)) 242 if err == nil { 243 tg.setenv("PWD", abs) 244 } 245 } 246 247 // sleep sleeps for one tick, where a tick is a conservative estimate 248 // of how long it takes for a file modification to get a different 249 // mtime. 250 func (tg *testgoData) sleep() { 251 time.Sleep(mtimeTick) 252 } 253 254 // setenv sets an environment variable to use when running the test go 255 // command. 256 func (tg *testgoData) setenv(name, val string) { 257 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) { 258 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val) 259 } 260 tg.unsetenv(name) 261 tg.env = append(tg.env, name+"="+val) 262 } 263 264 // unsetenv removes an environment variable. 265 func (tg *testgoData) unsetenv(name string) { 266 if tg.env == nil { 267 tg.env = append([]string(nil), os.Environ()...) 268 } 269 for i, v := range tg.env { 270 if strings.HasPrefix(v, name+"=") { 271 tg.env = append(tg.env[:i], tg.env[i+1:]...) 272 break 273 } 274 } 275 } 276 277 func (tg *testgoData) goTool() string { 278 if tg.wd == "" { 279 return "./testgo" + exeSuffix 280 } 281 return filepath.Join(tg.wd, "testgo"+exeSuffix) 282 } 283 284 // doRun runs the test go command, recording stdout and stderr and 285 // returning exit status. 286 func (tg *testgoData) doRun(args []string) error { 287 if !canRun { 288 panic("testgoData.doRun called but canRun false") 289 } 290 if tg.inParallel { 291 for _, arg := range args { 292 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") { 293 tg.t.Fatal("internal testsuite error: parallel run using testdata") 294 } 295 } 296 } 297 298 hasGoroot := false 299 for _, v := range tg.env { 300 if strings.HasPrefix(v, "GOROOT=") { 301 hasGoroot = true 302 break 303 } 304 } 305 prog := tg.goTool() 306 if !hasGoroot { 307 tg.setenv("GOROOT", testGOROOT) 308 } 309 310 tg.t.Logf("running testgo %v", args) 311 cmd := exec.Command(prog, args...) 312 tg.stdout.Reset() 313 tg.stderr.Reset() 314 cmd.Stdout = &tg.stdout 315 cmd.Stderr = &tg.stderr 316 cmd.Env = tg.env 317 status := cmd.Run() 318 if tg.stdout.Len() > 0 { 319 tg.t.Log("standard output:") 320 tg.t.Log(tg.stdout.String()) 321 } 322 if tg.stderr.Len() > 0 { 323 tg.t.Log("standard error:") 324 tg.t.Log(tg.stderr.String()) 325 } 326 tg.ran = true 327 return status 328 } 329 330 // run runs the test go command, and expects it to succeed. 331 func (tg *testgoData) run(args ...string) { 332 if status := tg.doRun(args); status != nil { 333 tg.t.Logf("go %v failed unexpectedly: %v", args, status) 334 tg.t.FailNow() 335 } 336 } 337 338 // runFail runs the test go command, and expects it to fail. 339 func (tg *testgoData) runFail(args ...string) { 340 if status := tg.doRun(args); status == nil { 341 tg.t.Fatal("testgo succeeded unexpectedly") 342 } else { 343 tg.t.Log("testgo failed as expected:", status) 344 } 345 } 346 347 // runGit runs a git command, and expects it to succeed. 348 func (tg *testgoData) runGit(dir string, args ...string) { 349 cmd := exec.Command("git", args...) 350 tg.stdout.Reset() 351 tg.stderr.Reset() 352 cmd.Stdout = &tg.stdout 353 cmd.Stderr = &tg.stderr 354 cmd.Dir = dir 355 cmd.Env = tg.env 356 status := cmd.Run() 357 if tg.stdout.Len() > 0 { 358 tg.t.Log("git standard output:") 359 tg.t.Log(tg.stdout.String()) 360 } 361 if tg.stderr.Len() > 0 { 362 tg.t.Log("git standard error:") 363 tg.t.Log(tg.stderr.String()) 364 } 365 if status != nil { 366 tg.t.Logf("git %v failed unexpectedly: %v", args, status) 367 tg.t.FailNow() 368 } 369 } 370 371 // getStdout returns standard output of the testgo run as a string. 372 func (tg *testgoData) getStdout() string { 373 if !tg.ran { 374 tg.t.Fatal("internal testsuite error: stdout called before run") 375 } 376 return tg.stdout.String() 377 } 378 379 // getStderr returns standard error of the testgo run as a string. 380 func (tg *testgoData) getStderr() string { 381 if !tg.ran { 382 tg.t.Fatal("internal testsuite error: stdout called before run") 383 } 384 return tg.stderr.String() 385 } 386 387 // doGrepMatch looks for a regular expression in a buffer, and returns 388 // whether it is found. The regular expression is matched against 389 // each line separately, as with the grep command. 390 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool { 391 if !tg.ran { 392 tg.t.Fatal("internal testsuite error: grep called before run") 393 } 394 re := regexp.MustCompile(match) 395 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) { 396 if re.Match(ln) { 397 return true 398 } 399 } 400 return false 401 } 402 403 // doGrep looks for a regular expression in a buffer and fails if it 404 // is not found. The name argument is the name of the output we are 405 // searching, "output" or "error". The msg argument is logged on 406 // failure. 407 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) { 408 if !tg.doGrepMatch(match, b) { 409 tg.t.Log(msg) 410 tg.t.Logf("pattern %v not found in standard %s", match, name) 411 tg.t.FailNow() 412 } 413 } 414 415 // grepStdout looks for a regular expression in the test run's 416 // standard output and fails, logging msg, if it is not found. 417 func (tg *testgoData) grepStdout(match, msg string) { 418 tg.doGrep(match, &tg.stdout, "output", msg) 419 } 420 421 // grepStderr looks for a regular expression in the test run's 422 // standard error and fails, logging msg, if it is not found. 423 func (tg *testgoData) grepStderr(match, msg string) { 424 tg.doGrep(match, &tg.stderr, "error", msg) 425 } 426 427 // grepBoth looks for a regular expression in the test run's standard 428 // output or stand error and fails, logging msg, if it is not found. 429 func (tg *testgoData) grepBoth(match, msg string) { 430 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) { 431 tg.t.Log(msg) 432 tg.t.Logf("pattern %v not found in standard output or standard error", match) 433 tg.t.FailNow() 434 } 435 } 436 437 // doGrepNot looks for a regular expression in a buffer and fails if 438 // it is found. The name and msg arguments are as for doGrep. 439 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) { 440 if tg.doGrepMatch(match, b) { 441 tg.t.Log(msg) 442 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name) 443 tg.t.FailNow() 444 } 445 } 446 447 // grepStdoutNot looks for a regular expression in the test run's 448 // standard output and fails, logging msg, if it is found. 449 func (tg *testgoData) grepStdoutNot(match, msg string) { 450 tg.doGrepNot(match, &tg.stdout, "output", msg) 451 } 452 453 // grepStderrNot looks for a regular expression in the test run's 454 // standard error and fails, logging msg, if it is found. 455 func (tg *testgoData) grepStderrNot(match, msg string) { 456 tg.doGrepNot(match, &tg.stderr, "error", msg) 457 } 458 459 // grepBothNot looks for a regular expression in the test run's 460 // standard output or stand error and fails, logging msg, if it is 461 // found. 462 func (tg *testgoData) grepBothNot(match, msg string) { 463 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) { 464 tg.t.Log(msg) 465 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match) 466 } 467 } 468 469 // doGrepCount counts the number of times a regexp is seen in a buffer. 470 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int { 471 if !tg.ran { 472 tg.t.Fatal("internal testsuite error: doGrepCount called before run") 473 } 474 re := regexp.MustCompile(match) 475 c := 0 476 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) { 477 if re.Match(ln) { 478 c++ 479 } 480 } 481 return c 482 } 483 484 // grepCountBoth returns the number of times a regexp is seen in both 485 // standard output and standard error. 486 func (tg *testgoData) grepCountBoth(match string) int { 487 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr) 488 } 489 490 // creatingTemp records that the test plans to create a temporary file 491 // or directory. If the file or directory exists already, it will be 492 // removed. When the test completes, the file or directory will be 493 // removed if it exists. 494 func (tg *testgoData) creatingTemp(path string) { 495 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) { 496 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path) 497 } 498 // If we have changed the working directory, make sure we have 499 // an absolute path, because we are going to change directory 500 // back before we remove the temporary. 501 if tg.wd != "" && !filepath.IsAbs(path) { 502 path = filepath.Join(tg.pwd(), path) 503 } 504 tg.must(os.RemoveAll(path)) 505 tg.temps = append(tg.temps, path) 506 } 507 508 // makeTempdir makes a temporary directory for a run of testgo. If 509 // the temporary directory was already created, this does nothing. 510 func (tg *testgoData) makeTempdir() { 511 if tg.tempdir == "" { 512 var err error 513 tg.tempdir, err = ioutil.TempDir("", "gotest") 514 tg.must(err) 515 } 516 } 517 518 // tempFile adds a temporary file for a run of testgo. 519 func (tg *testgoData) tempFile(path, contents string) { 520 tg.makeTempdir() 521 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755)) 522 bytes := []byte(contents) 523 if strings.HasSuffix(path, ".go") { 524 formatted, err := format.Source(bytes) 525 if err == nil { 526 bytes = formatted 527 } 528 } 529 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644)) 530 } 531 532 // tempDir adds a temporary directory for a run of testgo. 533 func (tg *testgoData) tempDir(path string) { 534 tg.makeTempdir() 535 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) { 536 tg.t.Fatal(err) 537 } 538 } 539 540 // path returns the absolute pathname to file with the temporary 541 // directory. 542 func (tg *testgoData) path(name string) string { 543 if tg.tempdir == "" { 544 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name) 545 } 546 if name == "." { 547 return tg.tempdir 548 } 549 return filepath.Join(tg.tempdir, name) 550 } 551 552 // mustExist fails if path does not exist. 553 func (tg *testgoData) mustExist(path string) { 554 if _, err := os.Stat(path); err != nil { 555 if os.IsNotExist(err) { 556 tg.t.Fatalf("%s does not exist but should", path) 557 } 558 tg.t.Fatalf("%s stat failed: %v", path, err) 559 } 560 } 561 562 // mustNotExist fails if path exists. 563 func (tg *testgoData) mustNotExist(path string) { 564 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) { 565 tg.t.Fatalf("%s exists but should not (%v)", path, err) 566 } 567 } 568 569 // wantExecutable fails with msg if path is not executable. 570 func (tg *testgoData) wantExecutable(path, msg string) { 571 if st, err := os.Stat(path); err != nil { 572 if !os.IsNotExist(err) { 573 tg.t.Log(err) 574 } 575 tg.t.Fatal(msg) 576 } else { 577 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 { 578 tg.t.Fatalf("binary %s exists but is not executable", path) 579 } 580 } 581 } 582 583 // wantArchive fails if path is not an archive. 584 func (tg *testgoData) wantArchive(path string) { 585 f, err := os.Open(path) 586 if err != nil { 587 tg.t.Fatal(err) 588 } 589 buf := make([]byte, 100) 590 io.ReadFull(f, buf) 591 f.Close() 592 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) { 593 tg.t.Fatalf("file %s exists but is not an archive", path) 594 } 595 } 596 597 // isStale reports whether pkg is stale, and why 598 func (tg *testgoData) isStale(pkg string) (bool, string) { 599 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg) 600 v := strings.TrimSpace(tg.getStdout()) 601 f := strings.SplitN(v, ":", 2) 602 if len(f) == 2 { 603 switch f[0] { 604 case "true": 605 return true, f[1] 606 case "false": 607 return false, f[1] 608 } 609 } 610 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v) 611 panic("unreachable") 612 } 613 614 // wantStale fails with msg if pkg is not stale. 615 func (tg *testgoData) wantStale(pkg, reason, msg string) { 616 stale, why := tg.isStale(pkg) 617 if !stale { 618 tg.t.Fatal(msg) 619 } 620 if reason == "" && why != "" || !strings.Contains(why, reason) { 621 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason) 622 } 623 } 624 625 // wantNotStale fails with msg if pkg is stale. 626 func (tg *testgoData) wantNotStale(pkg, reason, msg string) { 627 stale, why := tg.isStale(pkg) 628 if stale { 629 tg.t.Fatal(msg) 630 } 631 if reason == "" && why != "" || !strings.Contains(why, reason) { 632 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason) 633 } 634 } 635 636 // cleanup cleans up a test that runs testgo. 637 func (tg *testgoData) cleanup() { 638 if tg.wd != "" { 639 if err := os.Chdir(tg.wd); err != nil { 640 // We are unlikely to be able to continue. 641 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err) 642 os.Exit(2) 643 } 644 } 645 for _, path := range tg.temps { 646 tg.check(os.RemoveAll(path)) 647 } 648 if tg.tempdir != "" { 649 tg.check(os.RemoveAll(tg.tempdir)) 650 } 651 } 652 653 // failSSH puts an ssh executable in the PATH that always fails. 654 // This is to stub out uses of ssh by go get. 655 func (tg *testgoData) failSSH() { 656 wd, err := os.Getwd() 657 if err != nil { 658 tg.t.Fatal(err) 659 } 660 fail := filepath.Join(wd, "testdata/failssh") 661 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH"))) 662 } 663 664 func TestFileLineInErrorMessages(t *testing.T) { 665 tg := testgo(t) 666 defer tg.cleanup() 667 tg.parallel() 668 tg.tempFile("err.go", `package main; import "bar"`) 669 path := tg.path("err.go") 670 tg.runFail("run", path) 671 shortPath := path 672 if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) { 673 shortPath = rel 674 } 675 tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message") 676 } 677 678 func TestProgramNameInCrashMessages(t *testing.T) { 679 tg := testgo(t) 680 defer tg.cleanup() 681 tg.parallel() 682 tg.tempFile("triv.go", `package main; func main() {}`) 683 tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go")) 684 tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message") 685 } 686 687 func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) { 688 tg := testgo(t) 689 defer tg.cleanup() 690 // TODO: tg.parallel() 691 tg.runFail("test", "./testdata/src/badtest/...") 692 tg.grepBothNot("^ok", "test passed unexpectedly") 693 tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything") 694 tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything") 695 tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything") 696 } 697 698 func TestGoBuildDashAInDevBranch(t *testing.T) { 699 if testing.Short() { 700 t.Skip("don't rebuild the standard library in short mode") 701 } 702 703 tg := testgo(t) 704 defer tg.cleanup() 705 tg.run("install", "math") // should be up to date already but just in case 706 tg.setenv("TESTGO_IS_GO_RELEASE", "0") 707 tg.run("build", "-v", "-a", "math") 708 tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have") 709 710 // Everything is out of date. Rebuild to leave things in a better state. 711 tg.run("install", "std") 712 } 713 714 func TestGoBuildDashAInReleaseBranch(t *testing.T) { 715 if testing.Short() { 716 t.Skip("don't rebuild the standard library in short mode") 717 } 718 719 tg := testgo(t) 720 defer tg.cleanup() 721 tg.run("install", "math", "net/http") // should be up to date already but just in case 722 tg.setenv("TESTGO_IS_GO_RELEASE", "1") 723 tg.run("install", "-v", "-a", "math") 724 tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have") 725 726 // Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release. 727 tg.run("build", "-v", "net/http") 728 tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have") 729 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") 730 tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have") 731 732 // Everything is out of date. Rebuild to leave things in a better state. 733 tg.run("install", "std") 734 } 735 736 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) { 737 if testing.Short() { 738 t.Skip("don't rebuild the standard library in short mode") 739 } 740 741 tg := testgo(t) 742 defer tg.cleanup() 743 744 addNL := func(name string) (restore func()) { 745 data, err := ioutil.ReadFile(name) 746 if err != nil { 747 t.Fatal(err) 748 } 749 old := data 750 data = append(data, '\n') 751 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil { 752 t.Fatal(err) 753 } 754 tg.sleep() 755 return func() { 756 if err := ioutil.WriteFile(name, old, 0666); err != nil { 757 t.Fatal(err) 758 } 759 } 760 } 761 762 tg.setenv("TESTGO_IS_GO_RELEASE", "1") 763 764 tg.tempFile("d1/src/p1/p1.go", `package p1`) 765 tg.setenv("GOPATH", tg.path("d1")) 766 tg.run("install", "-a", "p1") 767 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly") 768 tg.sleep() 769 770 // Changing mtime and content of runtime/internal/sys/sys.go 771 // should have no effect: we're in a release, which doesn't rebuild 772 // for general mtime or content changes. 773 sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go" 774 restore := addNL(sys) 775 defer restore() 776 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating runtime/internal/sys/sys.go") 777 restore() 778 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after restoring runtime/internal/sys/sys.go") 779 780 // But changing runtime/internal/sys/zversion.go should have an effect: 781 // that's how we tell when we flip from one release to another. 782 zversion := runtime.GOROOT() + "/src/runtime/internal/sys/zversion.go" 783 restore = addNL(zversion) 784 defer restore() 785 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to new release") 786 restore() 787 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release") 788 addNL(zversion) 789 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing again to new release") 790 tg.run("install", "p1") 791 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release") 792 793 // Restore to "old" release. 794 restore() 795 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to old release after new build") 796 tg.run("install", "p1") 797 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release") 798 799 // Everything is out of date. Rebuild to leave things in a better state. 800 tg.run("install", "std") 801 } 802 803 func TestGoListStandard(t *testing.T) { 804 tg := testgo(t) 805 defer tg.cleanup() 806 // TODO: tg.parallel() 807 tg.cd(runtime.GOROOT() + "/src") 808 tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...") 809 stdout := tg.getStdout() 810 for _, line := range strings.Split(stdout, "\n") { 811 if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") { 812 // $GOROOT/src shows up if there are any .go files there. 813 // We don't care. 814 continue 815 } 816 if line == "" { 817 continue 818 } 819 t.Errorf("package in GOROOT not listed as standard: %v", line) 820 } 821 822 // Similarly, expanding std should include some of our vendored code. 823 tg.run("list", "std", "cmd") 824 tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack") 825 tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm") 826 } 827 828 func TestGoInstallCleansUpAfterGoBuild(t *testing.T) { 829 tg := testgo(t) 830 defer tg.cleanup() 831 // TODO: tg.parallel() 832 tg.tempFile("src/mycmd/main.go", `package main; func main(){}`) 833 tg.setenv("GOPATH", tg.path(".")) 834 tg.cd(tg.path("src/mycmd")) 835 836 doesNotExist := func(file, msg string) { 837 if _, err := os.Stat(file); err == nil { 838 t.Fatal(msg) 839 } else if !os.IsNotExist(err) { 840 t.Fatal(msg, "error:", err) 841 } 842 } 843 844 tg.run("build") 845 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary") 846 tg.run("install") 847 doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary") 848 tg.run("build") 849 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)") 850 // Running install with arguments does not remove the target, 851 // even in the same directory. 852 tg.run("install", "mycmd") 853 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd") 854 tg.run("build") 855 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)") 856 // And especially not outside the directory. 857 tg.cd(tg.path(".")) 858 if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil { 859 t.Fatal("could not read file:", err) 860 } else { 861 if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil { 862 t.Fatal("could not write file:", err) 863 } 864 } 865 tg.run("install", "mycmd") 866 tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd") 867 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd") 868 } 869 870 func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) { 871 tg := testgo(t) 872 defer tg.cleanup() 873 tg.parallel() 874 tg.tempFile("d1/src/p1/p1.go", `package p1 875 import "p2" 876 func F() { p2.F() }`) 877 tg.tempFile("d2/src/p2/p2.go", `package p2 878 func F() {}`) 879 sep := string(filepath.ListSeparator) 880 tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2")) 881 tg.run("install", "p1") 882 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly") 883 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly") 884 tg.sleep() 885 if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil { 886 t.Fatal(err) 887 } else if _, err = f.WriteString(`func G() {}`); err != nil { 888 t.Fatal(err) 889 } else { 890 tg.must(f.Close()) 891 } 892 tg.wantStale("p2", "newer source file", "./testgo list claims p2 is NOT stale, incorrectly") 893 tg.wantStale("p1", "stale dependency", "./testgo list claims p1 is NOT stale, incorrectly") 894 895 tg.run("install", "p1") 896 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly") 897 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly") 898 } 899 900 func TestGoInstallDetectsRemovedFiles(t *testing.T) { 901 tg := testgo(t) 902 defer tg.cleanup() 903 tg.parallel() 904 tg.tempFile("src/mypkg/x.go", `package mypkg`) 905 tg.tempFile("src/mypkg/y.go", `package mypkg`) 906 tg.tempFile("src/mypkg/z.go", `// +build missingtag 907 908 package mypkg`) 909 tg.setenv("GOPATH", tg.path(".")) 910 tg.run("install", "mypkg") 911 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly") 912 // z.go was not part of the build; removing it is okay. 913 tg.must(os.Remove(tg.path("src/mypkg/z.go"))) 914 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale") 915 // y.go was part of the package; removing it should be detected. 916 tg.must(os.Remove(tg.path("src/mypkg/y.go"))) 917 tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale") 918 } 919 920 func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) { 921 tg := testgo(t) 922 defer tg.cleanup() 923 // TODO: tg.parallel() 924 tg.tempFile("src/mypkg/x.go", `package mypkg`) 925 tg.tempFile("src/mypkg/y.go", `pkg mypackage`) 926 tg.setenv("GOPATH", tg.path(".")) 927 tg.cd(tg.path("src/mypkg")) 928 tg.runFail("list", "./...") 929 tg.runFail("build", "./...") 930 tg.runFail("install", "./...") 931 } 932 933 func TestGoListWithTags(t *testing.T) { 934 tg := testgo(t) 935 defer tg.cleanup() 936 tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n") 937 tg.setenv("GOPATH", tg.path(".")) 938 tg.cd(tg.path("./src")) 939 tg.run("list", "-tags=thetag", "./my...") 940 tg.grepStdout("mypkg", "did not find mypkg") 941 } 942 943 func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) { 944 if testing.Short() { 945 t.Skip("don't install into GOROOT in short mode") 946 } 947 948 tg := testgo(t) 949 defer tg.cleanup() 950 tg.tempFile("src/mycmd/x.go", `package main 951 func main() {}`) 952 tg.setenv("GOPATH", tg.path(".")) 953 tg.cd(tg.path("src/mycmd")) 954 955 tg.run("build", "mycmd") 956 957 goarch := "386" 958 if runtime.GOARCH == "386" { 959 goarch = "amd64" 960 } 961 tg.setenv("GOOS", "linux") 962 tg.setenv("GOARCH", goarch) 963 tg.run("install", "mycmd") 964 tg.setenv("GOBIN", tg.path(".")) 965 tg.runFail("install", "mycmd") 966 tg.run("install", "cmd/pack") 967 } 968 969 func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) { 970 tg := testgo(t) 971 defer tg.cleanup() 972 tg.parallel() 973 tg.tempFile("src/mycmd/x.go", `package main 974 func main() {}`) 975 tg.tempFile("src/mycmd/y.go", `package main`) 976 tg.tempFile("src/mycmd/z.go", `// +build missingtag 977 978 package main`) 979 tg.setenv("GOPATH", tg.path(".")) 980 tg.run("install", "mycmd") 981 tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly") 982 // z.go was not part of the build; removing it is okay. 983 tg.must(os.Remove(tg.path("src/mycmd/z.go"))) 984 tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale") 985 // y.go was part of the package; removing it should be detected. 986 tg.must(os.Remove(tg.path("src/mycmd/y.go"))) 987 tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale") 988 } 989 990 func testLocalRun(tg *testgoData, exepath, local, match string) { 991 out, err := exec.Command(exepath).Output() 992 if err != nil { 993 tg.t.Fatalf("error running %v: %v", exepath, err) 994 } 995 if !regexp.MustCompile(match).Match(out) { 996 tg.t.Log(string(out)) 997 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local) 998 } 999 } 1000 1001 func testLocalEasy(tg *testgoData, local string) { 1002 exepath := "./easy" + exeSuffix 1003 tg.creatingTemp(exepath) 1004 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go")) 1005 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`) 1006 } 1007 1008 func testLocalEasySub(tg *testgoData, local string) { 1009 exepath := "./easysub" + exeSuffix 1010 tg.creatingTemp(exepath) 1011 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go")) 1012 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`) 1013 } 1014 1015 func testLocalHard(tg *testgoData, local string) { 1016 exepath := "./hard" + exeSuffix 1017 tg.creatingTemp(exepath) 1018 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go")) 1019 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`) 1020 } 1021 1022 func testLocalInstall(tg *testgoData, local string) { 1023 tg.runFail("install", filepath.Join("testdata", local, "easy.go")) 1024 } 1025 1026 func TestLocalImportsEasy(t *testing.T) { 1027 tg := testgo(t) 1028 defer tg.cleanup() 1029 testLocalEasy(tg, "local") 1030 } 1031 1032 func TestLocalImportsEasySub(t *testing.T) { 1033 tg := testgo(t) 1034 defer tg.cleanup() 1035 testLocalEasySub(tg, "local") 1036 } 1037 1038 func TestLocalImportsHard(t *testing.T) { 1039 tg := testgo(t) 1040 defer tg.cleanup() 1041 testLocalHard(tg, "local") 1042 } 1043 1044 func TestLocalImportsGoInstallShouldFail(t *testing.T) { 1045 tg := testgo(t) 1046 defer tg.cleanup() 1047 testLocalInstall(tg, "local") 1048 } 1049 1050 const badDirName = `#$%:, &()*;<=>?\^{}` 1051 1052 func copyBad(tg *testgoData) { 1053 if runtime.GOOS == "windows" { 1054 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName) 1055 } 1056 1057 tg.must(filepath.Walk("testdata/local", 1058 func(path string, info os.FileInfo, err error) error { 1059 if err != nil { 1060 return err 1061 } 1062 if info.IsDir() { 1063 return nil 1064 } 1065 var data []byte 1066 data, err = ioutil.ReadFile(path) 1067 if err != nil { 1068 return err 1069 } 1070 newpath := strings.Replace(path, "local", badDirName, 1) 1071 tg.tempFile(newpath, string(data)) 1072 return nil 1073 })) 1074 tg.cd(tg.path(".")) 1075 } 1076 1077 func TestBadImportsEasy(t *testing.T) { 1078 tg := testgo(t) 1079 defer tg.cleanup() 1080 // TODO: tg.parallel() 1081 copyBad(tg) 1082 testLocalEasy(tg, badDirName) 1083 } 1084 1085 func TestBadImportsEasySub(t *testing.T) { 1086 tg := testgo(t) 1087 defer tg.cleanup() 1088 copyBad(tg) 1089 testLocalEasySub(tg, badDirName) 1090 } 1091 1092 func TestBadImportsHard(t *testing.T) { 1093 tg := testgo(t) 1094 defer tg.cleanup() 1095 copyBad(tg) 1096 testLocalHard(tg, badDirName) 1097 } 1098 1099 func TestBadImportsGoInstallShouldFail(t *testing.T) { 1100 tg := testgo(t) 1101 defer tg.cleanup() 1102 copyBad(tg) 1103 testLocalInstall(tg, badDirName) 1104 } 1105 1106 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) { 1107 tg := testgo(t) 1108 defer tg.cleanup() 1109 tg.runFail("build", "-v", "./testdata/testinternal") 1110 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal") 1111 } 1112 1113 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) { 1114 tg := testgo(t) 1115 defer tg.cleanup() 1116 tg.runFail("build", "-v", "./testdata/testinternal2") 1117 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2") 1118 } 1119 1120 func TestRunInternal(t *testing.T) { 1121 tg := testgo(t) 1122 defer tg.cleanup() 1123 dir := filepath.Join(tg.pwd(), "testdata") 1124 tg.setenv("GOPATH", dir) 1125 tg.run("run", filepath.Join(dir, "src/run/good.go")) 1126 tg.runFail("run", filepath.Join(dir, "src/run/bad.go")) 1127 tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go") 1128 } 1129 1130 func testMove(t *testing.T, vcs, url, base, config string) { 1131 testenv.MustHaveExternalNetwork(t) 1132 1133 tg := testgo(t) 1134 defer tg.cleanup() 1135 tg.parallel() 1136 tg.tempDir("src") 1137 tg.setenv("GOPATH", tg.path(".")) 1138 tg.run("get", "-d", url) 1139 tg.run("get", "-d", "-u", url) 1140 switch vcs { 1141 case "svn": 1142 // SVN doesn't believe in text files so we can't just edit the config. 1143 // Check out a different repo into the wrong place. 1144 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn"))) 1145 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk") 1146 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn"))) 1147 default: 1148 path := tg.path(filepath.Join("src", config)) 1149 data, err := ioutil.ReadFile(path) 1150 tg.must(err) 1151 data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1) 1152 tg.must(ioutil.WriteFile(path, data, 0644)) 1153 } 1154 if vcs == "git" { 1155 // git will ask for a username and password when we 1156 // run go get -d -f -u. An empty username and 1157 // password will work. Prevent asking by setting 1158 // GIT_ASKPASS. 1159 tg.creatingTemp("sink" + exeSuffix) 1160 tg.tempFile("src/sink/sink.go", `package main; func main() {}`) 1161 tg.run("build", "-o", "sink"+exeSuffix, "sink") 1162 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix)) 1163 } 1164 tg.runFail("get", "-d", "-u", url) 1165 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason") 1166 tg.runFail("get", "-d", "-f", "-u", url) 1167 tg.grepStderr("validating server certificate|not found", "go get -d -f -u "+url+" failed for wrong reason") 1168 } 1169 1170 func TestInternalPackageErrorsAreHandled(t *testing.T) { 1171 tg := testgo(t) 1172 defer tg.cleanup() 1173 tg.run("list", "./testdata/testinternal3") 1174 } 1175 1176 func TestInternalCache(t *testing.T) { 1177 tg := testgo(t) 1178 defer tg.cleanup() 1179 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4")) 1180 tg.runFail("build", "p") 1181 tg.grepStderr("internal", "did not fail to build p") 1182 } 1183 1184 func TestMoveGit(t *testing.T) { 1185 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config") 1186 } 1187 1188 // TODO(rsc): Set up a test case on bitbucket for hg. 1189 // func TestMoveHG(t *testing.T) { 1190 // testMove(t, "hg", "rsc.io/x86/x86asm", "x86", "rsc.io/x86/.hg/hgrc") 1191 // } 1192 1193 // TODO(rsc): Set up a test case on SourceForge (?) for svn. 1194 // func testMoveSVN(t *testing.T) { 1195 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-") 1196 // } 1197 1198 func TestImportCommandMatch(t *testing.T) { 1199 tg := testgo(t) 1200 defer tg.cleanup() 1201 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1202 tg.run("build", "./testdata/importcom/works.go") 1203 } 1204 1205 func TestImportCommentMismatch(t *testing.T) { 1206 tg := testgo(t) 1207 defer tg.cleanup() 1208 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1209 tg.runFail("build", "./testdata/importcom/wrongplace.go") 1210 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import") 1211 } 1212 1213 func TestImportCommentSyntaxError(t *testing.T) { 1214 tg := testgo(t) 1215 defer tg.cleanup() 1216 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1217 tg.runFail("build", "./testdata/importcom/bad.go") 1218 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error") 1219 } 1220 1221 func TestImportCommentConflict(t *testing.T) { 1222 tg := testgo(t) 1223 defer tg.cleanup() 1224 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1225 tg.runFail("build", "./testdata/importcom/conflict.go") 1226 tg.grepStderr("found import comments", "go build did not mention comment conflict") 1227 } 1228 1229 // cmd/go: custom import path checking should not apply to Go packages without import comment. 1230 func TestIssue10952(t *testing.T) { 1231 testenv.MustHaveExternalNetwork(t) 1232 if _, err := exec.LookPath("git"); err != nil { 1233 t.Skip("skipping because git binary not found") 1234 } 1235 1236 tg := testgo(t) 1237 defer tg.cleanup() 1238 tg.parallel() 1239 tg.tempDir("src") 1240 tg.setenv("GOPATH", tg.path(".")) 1241 const importPath = "github.com/zombiezen/go-get-issue-10952" 1242 tg.run("get", "-d", "-u", importPath) 1243 repoDir := tg.path("src/" + importPath) 1244 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git") 1245 tg.run("get", "-d", "-u", importPath) 1246 } 1247 1248 func TestIssue16471(t *testing.T) { 1249 testenv.MustHaveExternalNetwork(t) 1250 if _, err := exec.LookPath("git"); err != nil { 1251 t.Skip("skipping because git binary not found") 1252 } 1253 1254 tg := testgo(t) 1255 defer tg.cleanup() 1256 tg.parallel() 1257 tg.tempDir("src") 1258 tg.setenv("GOPATH", tg.path(".")) 1259 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755)) 1260 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952") 1261 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952") 1262 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") 1263 } 1264 1265 // Test git clone URL that uses SCP-like syntax and custom import path checking. 1266 func TestIssue11457(t *testing.T) { 1267 testenv.MustHaveExternalNetwork(t) 1268 if _, err := exec.LookPath("git"); err != nil { 1269 t.Skip("skipping because git binary not found") 1270 } 1271 1272 tg := testgo(t) 1273 defer tg.cleanup() 1274 tg.parallel() 1275 tg.tempDir("src") 1276 tg.setenv("GOPATH", tg.path(".")) 1277 const importPath = "rsc.io/go-get-issue-11457" 1278 tg.run("get", "-d", "-u", importPath) 1279 repoDir := tg.path("src/" + importPath) 1280 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457") 1281 1282 // At this time, custom import path checking compares remotes verbatim (rather than 1283 // just the host and path, skipping scheme and user), so we expect go get -u to fail. 1284 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed 1285 // the SCP-like syntax, and we expect it to appear in the error message. 1286 tg.runFail("get", "-d", "-u", importPath) 1287 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457" 1288 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) { 1289 t.Error("expected clone URL to appear in stderr") 1290 } 1291 } 1292 1293 func TestGetGitDefaultBranch(t *testing.T) { 1294 testenv.MustHaveExternalNetwork(t) 1295 if _, err := exec.LookPath("git"); err != nil { 1296 t.Skip("skipping because git binary not found") 1297 } 1298 1299 tg := testgo(t) 1300 defer tg.cleanup() 1301 tg.parallel() 1302 tg.tempDir("src") 1303 tg.setenv("GOPATH", tg.path(".")) 1304 1305 // This repo has two branches, master and another-branch. 1306 // The another-branch is the default that you get from 'git clone'. 1307 // The go get command variants should not override this. 1308 const importPath = "github.com/rsc/go-get-default-branch" 1309 1310 tg.run("get", "-d", importPath) 1311 repoDir := tg.path("src/" + importPath) 1312 tg.runGit(repoDir, "branch", "--contains", "HEAD") 1313 tg.grepStdout(`\* another-branch`, "not on correct default branch") 1314 1315 tg.run("get", "-d", "-u", importPath) 1316 tg.runGit(repoDir, "branch", "--contains", "HEAD") 1317 tg.grepStdout(`\* another-branch`, "not on correct default branch") 1318 } 1319 1320 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) { 1321 tg := testgo(t) 1322 defer tg.cleanup() 1323 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1324 tg.runFail("test", "syntaxerror") 1325 tg.grepStderr("FAIL", "go test did not say FAIL") 1326 } 1327 1328 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) { 1329 tg := testgo(t) 1330 defer tg.cleanup() 1331 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1332 tg.runFail("list", "...") 1333 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg") 1334 tg.run("list", "m...") 1335 } 1336 1337 func TestRelativeImportsGoTest(t *testing.T) { 1338 tg := testgo(t) 1339 defer tg.cleanup() 1340 tg.run("test", "./testdata/testimport") 1341 } 1342 1343 func TestRelativeImportsGoTestDashI(t *testing.T) { 1344 tg := testgo(t) 1345 defer tg.cleanup() 1346 tg.run("test", "-i", "./testdata/testimport") 1347 } 1348 1349 func TestRelativeImportsInCommandLinePackage(t *testing.T) { 1350 tg := testgo(t) 1351 defer tg.cleanup() 1352 // TODO: tg.parallel() 1353 files, err := filepath.Glob("./testdata/testimport/*.go") 1354 tg.must(err) 1355 tg.run(append([]string{"test"}, files...)...) 1356 } 1357 1358 func TestNonCanonicalImportPaths(t *testing.T) { 1359 tg := testgo(t) 1360 defer tg.cleanup() 1361 tg.parallel() 1362 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1363 tg.runFail("build", "canonical/d") 1364 tg.grepStderr("package canonical/d", "did not report canonical/d") 1365 tg.grepStderr("imports canonical/b", "did not report canonical/b") 1366 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/") 1367 } 1368 1369 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) { 1370 tg := testgo(t) 1371 defer tg.cleanup() 1372 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1")) 1373 tg.runFail("get", "-u", "foo") 1374 1375 // TODO(iant): We should not have to use strconv.Quote here. 1376 // The code in vcs.go should be changed so that it is not required. 1377 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo")) 1378 quoted = quoted[1 : len(quoted)-1] 1379 1380 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo") 1381 } 1382 1383 func TestInstallFailsWithNoBuildableFiles(t *testing.T) { 1384 tg := testgo(t) 1385 defer tg.cleanup() 1386 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1387 tg.setenv("CGO_ENABLED", "0") 1388 tg.runFail("install", "cgotest") 1389 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'") 1390 } 1391 1392 func TestRelativeGOBINFail(t *testing.T) { 1393 tg := testgo(t) 1394 defer tg.cleanup() 1395 tg.tempFile("triv.go", `package main; func main() {}`) 1396 tg.setenv("GOBIN", ".") 1397 tg.runFail("install") 1398 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path") 1399 } 1400 1401 // Test that without $GOBIN set, binaries get installed 1402 // into the GOPATH bin directory. 1403 func TestInstallIntoGOPATH(t *testing.T) { 1404 tg := testgo(t) 1405 defer tg.cleanup() 1406 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix) 1407 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1408 tg.run("install", "go-cmd-test") 1409 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test") 1410 } 1411 1412 // Issue 12407 1413 func TestBuildOutputToDevNull(t *testing.T) { 1414 tg := testgo(t) 1415 defer tg.cleanup() 1416 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1417 tg.run("build", "-o", os.DevNull, "go-cmd-test") 1418 } 1419 1420 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) { 1421 tg := testgo(t) 1422 defer tg.cleanup() 1423 tg.parallel() 1424 gobin := filepath.Join(tg.pwd(), "testdata", "bin") 1425 tg.creatingTemp(gobin) 1426 tg.setenv("GOBIN", gobin) 1427 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1428 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now())) 1429 tg.sleep() 1430 tg.run("test", "main_test") 1431 tg.run("install", "main_test") 1432 tg.wantNotStale("main_test", "", "after go install, main listed as stale") 1433 tg.run("test", "main_test") 1434 } 1435 1436 // The runtime version string takes one of two forms: 1437 // "go1.X[.Y]" for Go releases, and "devel +hash" at tip. 1438 // Determine whether we are in a released copy by 1439 // inspecting the version. 1440 var isGoRelease = strings.HasPrefix(runtime.Version(), "go1") 1441 1442 // Issue 12690 1443 func TestPackageNotStaleWithTrailingSlash(t *testing.T) { 1444 tg := testgo(t) 1445 defer tg.cleanup() 1446 1447 // Make sure the packages below are not stale. 1448 tg.run("install", "runtime", "os", "io") 1449 1450 goroot := runtime.GOROOT() 1451 tg.setenv("GOROOT", goroot+"/") 1452 1453 want := "" 1454 if isGoRelease { 1455 want = "standard package in Go release distribution" 1456 } 1457 1458 tg.wantNotStale("runtime", want, "with trailing slash in GOROOT, runtime listed as stale") 1459 tg.wantNotStale("os", want, "with trailing slash in GOROOT, os listed as stale") 1460 tg.wantNotStale("io", want, "with trailing slash in GOROOT, io listed as stale") 1461 } 1462 1463 // With $GOBIN set, binaries get installed to $GOBIN. 1464 func TestInstallIntoGOBIN(t *testing.T) { 1465 tg := testgo(t) 1466 defer tg.cleanup() 1467 gobin := filepath.Join(tg.pwd(), "testdata", "bin1") 1468 tg.creatingTemp(gobin) 1469 tg.setenv("GOBIN", gobin) 1470 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1471 tg.run("install", "go-cmd-test") 1472 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test") 1473 } 1474 1475 // Issue 11065 1476 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) { 1477 tg := testgo(t) 1478 defer tg.cleanup() 1479 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test") 1480 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix)) 1481 tg.setenv("GOBIN", pkg) 1482 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1483 tg.cd(pkg) 1484 tg.run("install") 1485 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory") 1486 } 1487 1488 // Without $GOBIN set, installing a program outside $GOPATH should fail 1489 // (there is nowhere to install it). 1490 func TestInstallWithoutDestinationFails(t *testing.T) { 1491 tg := testgo(t) 1492 defer tg.cleanup() 1493 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go") 1494 tg.grepStderr("no install location for .go files listed on command line", "wrong error") 1495 } 1496 1497 // With $GOBIN set, should install there. 1498 func TestInstallToGOBINCommandLinePackage(t *testing.T) { 1499 tg := testgo(t) 1500 defer tg.cleanup() 1501 gobin := filepath.Join(tg.pwd(), "testdata", "bin1") 1502 tg.creatingTemp(gobin) 1503 tg.setenv("GOBIN", gobin) 1504 tg.run("install", "testdata/src/go-cmd-test/helloworld.go") 1505 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld") 1506 } 1507 1508 func TestGoGetNonPkg(t *testing.T) { 1509 testenv.MustHaveExternalNetwork(t) 1510 1511 tg := testgo(t) 1512 defer tg.cleanup() 1513 tg.tempDir("gobin") 1514 tg.setenv("GOPATH", tg.path(".")) 1515 tg.setenv("GOBIN", tg.path("gobin")) 1516 tg.runFail("get", "-d", "golang.org/x/tools") 1517 tg.grepStderr("golang.org/x/tools: no Go files", "missing error") 1518 tg.runFail("get", "-d", "-u", "golang.org/x/tools") 1519 tg.grepStderr("golang.org/x/tools: no Go files", "missing error") 1520 tg.runFail("get", "-d", "golang.org/x/tools") 1521 tg.grepStderr("golang.org/x/tools: no Go files", "missing error") 1522 } 1523 1524 func TestGoGetTestOnlyPkg(t *testing.T) { 1525 testenv.MustHaveExternalNetwork(t) 1526 1527 tg := testgo(t) 1528 defer tg.cleanup() 1529 tg.tempDir("gopath") 1530 tg.setenv("GOPATH", tg.path("gopath")) 1531 tg.run("get", "golang.org/x/tour/content") 1532 tg.run("get", "-t", "golang.org/x/tour/content") 1533 } 1534 1535 func TestInstalls(t *testing.T) { 1536 if testing.Short() { 1537 t.Skip("don't install into GOROOT in short mode") 1538 } 1539 1540 tg := testgo(t) 1541 defer tg.cleanup() 1542 tg.parallel() 1543 tg.tempDir("gobin") 1544 tg.setenv("GOPATH", tg.path(".")) 1545 goroot := runtime.GOROOT() 1546 tg.setenv("GOROOT", goroot) 1547 1548 // cmd/fix installs into tool 1549 tg.run("env", "GOOS") 1550 goos := strings.TrimSpace(tg.getStdout()) 1551 tg.setenv("GOOS", goos) 1552 tg.run("env", "GOARCH") 1553 goarch := strings.TrimSpace(tg.getStdout()) 1554 tg.setenv("GOARCH", goarch) 1555 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix 1556 tg.must(os.RemoveAll(fixbin)) 1557 tg.run("install", "cmd/fix") 1558 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool") 1559 tg.must(os.Remove(fixbin)) 1560 tg.setenv("GOBIN", tg.path("gobin")) 1561 tg.run("install", "cmd/fix") 1562 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set") 1563 tg.unsetenv("GOBIN") 1564 1565 // gopath program installs into GOBIN 1566 tg.tempFile("src/progname/p.go", `package main; func main() {}`) 1567 tg.setenv("GOBIN", tg.path("gobin")) 1568 tg.run("install", "progname") 1569 tg.unsetenv("GOBIN") 1570 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname") 1571 1572 // gopath program installs into GOPATH/bin 1573 tg.run("install", "progname") 1574 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname") 1575 } 1576 1577 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) { 1578 tg := testgo(t) 1579 defer tg.cleanup() 1580 tg.setenv("GOPATH", ".") 1581 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go") 1582 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1583 } 1584 1585 func TestRejectRelativePathsInGOPATH(t *testing.T) { 1586 tg := testgo(t) 1587 defer tg.cleanup() 1588 sep := string(filepath.ListSeparator) 1589 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".") 1590 tg.runFail("build", "go-cmd-test") 1591 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1592 } 1593 1594 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) { 1595 tg := testgo(t) 1596 defer tg.cleanup() 1597 tg.setenv("GOPATH", "testdata") 1598 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go") 1599 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1600 } 1601 1602 // Issue 4104. 1603 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) { 1604 tg := testgo(t) 1605 defer tg.cleanup() 1606 tg.parallel() 1607 tg.run("test", "errors", "errors", "errors", "errors", "errors") 1608 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") { 1609 t.Error("go test errors errors errors errors errors tested the same package multiple times") 1610 } 1611 } 1612 1613 func TestGoListHasAConsistentOrder(t *testing.T) { 1614 tg := testgo(t) 1615 defer tg.cleanup() 1616 tg.parallel() 1617 tg.run("list", "std") 1618 first := tg.getStdout() 1619 tg.run("list", "std") 1620 if first != tg.getStdout() { 1621 t.Error("go list std ordering is inconsistent") 1622 } 1623 } 1624 1625 func TestGoListStdDoesNotIncludeCommands(t *testing.T) { 1626 tg := testgo(t) 1627 defer tg.cleanup() 1628 tg.parallel() 1629 tg.run("list", "std") 1630 tg.grepStdoutNot("cmd/", "go list std shows commands") 1631 } 1632 1633 func TestGoListCmdOnlyShowsCommands(t *testing.T) { 1634 tg := testgo(t) 1635 defer tg.cleanup() 1636 tg.parallel() 1637 tg.run("list", "cmd") 1638 out := strings.TrimSpace(tg.getStdout()) 1639 for _, line := range strings.Split(out, "\n") { 1640 if !strings.Contains(line, "cmd/") { 1641 t.Error("go list cmd shows non-commands") 1642 break 1643 } 1644 } 1645 } 1646 1647 func TestGoListDedupsPackages(t *testing.T) { 1648 tg := testgo(t) 1649 defer tg.cleanup() 1650 // TODO: tg.parallel() 1651 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1652 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...") 1653 got := strings.TrimSpace(tg.getStdout()) 1654 const want = "xtestonly" 1655 if got != want { 1656 t.Errorf("got %q; want %q", got, want) 1657 } 1658 } 1659 1660 // Issue 4096. Validate the output of unsuccessful go install foo/quxx. 1661 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) { 1662 tg := testgo(t) 1663 defer tg.cleanup() 1664 tg.parallel() 1665 tg.runFail("install", "foo/quxx") 1666 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 { 1667 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`) 1668 } 1669 } 1670 1671 func TestGOROOTSearchFailureReporting(t *testing.T) { 1672 tg := testgo(t) 1673 defer tg.cleanup() 1674 tg.parallel() 1675 tg.runFail("install", "foo/quxx") 1676 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 { 1677 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`) 1678 } 1679 } 1680 1681 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) { 1682 tg := testgo(t) 1683 defer tg.cleanup() 1684 tg.parallel() 1685 sep := string(filepath.ListSeparator) 1686 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1687 tg.runFail("install", "foo/quxx") 1688 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 { 1689 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`) 1690 } 1691 } 1692 1693 // Test (from $GOPATH) annotation is reported for the first GOPATH entry, 1694 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) { 1695 tg := testgo(t) 1696 defer tg.cleanup() 1697 tg.parallel() 1698 sep := string(filepath.ListSeparator) 1699 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1700 tg.runFail("install", "foo/quxx") 1701 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 { 1702 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`) 1703 } 1704 } 1705 1706 // but not on the second. 1707 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) { 1708 tg := testgo(t) 1709 defer tg.cleanup() 1710 tg.parallel() 1711 sep := string(filepath.ListSeparator) 1712 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1713 tg.runFail("install", "foo/quxx") 1714 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 { 1715 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`) 1716 } 1717 } 1718 1719 func homeEnvName() string { 1720 switch runtime.GOOS { 1721 case "windows": 1722 return "USERPROFILE" 1723 case "plan9": 1724 return "home" 1725 default: 1726 return "HOME" 1727 } 1728 } 1729 1730 func TestDefaultGOPATH(t *testing.T) { 1731 tg := testgo(t) 1732 defer tg.cleanup() 1733 tg.parallel() 1734 tg.tempDir("home/go") 1735 tg.setenv(homeEnvName(), tg.path("home")) 1736 1737 tg.run("env", "GOPATH") 1738 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go") 1739 1740 tg.setenv("GOROOT", tg.path("home/go")) 1741 tg.run("env", "GOPATH") 1742 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go") 1743 1744 tg.setenv("GOROOT", tg.path("home/go")+"/") 1745 tg.run("env", "GOPATH") 1746 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/") 1747 } 1748 1749 func TestDefaultGOPATHGet(t *testing.T) { 1750 testenv.MustHaveExternalNetwork(t) 1751 1752 tg := testgo(t) 1753 defer tg.cleanup() 1754 tg.setenv("GOPATH", "") 1755 tg.tempDir("home") 1756 tg.setenv(homeEnvName(), tg.path("home")) 1757 1758 // warn for creating directory 1759 tg.run("get", "-v", "github.com/golang/example/hello") 1760 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH") 1761 1762 // no warning if directory already exists 1763 tg.must(os.RemoveAll(tg.path("home/go"))) 1764 tg.tempDir("home/go") 1765 tg.run("get", "github.com/golang/example/hello") 1766 tg.grepStderrNot(".", "expected no output on standard error") 1767 1768 // error if $HOME/go is a file 1769 tg.must(os.RemoveAll(tg.path("home/go"))) 1770 tg.tempFile("home/go", "") 1771 tg.runFail("get", "github.com/golang/example/hello") 1772 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file") 1773 } 1774 1775 func TestDefaultGOPATHPrintedSearchList(t *testing.T) { 1776 tg := testgo(t) 1777 defer tg.cleanup() 1778 tg.setenv("GOPATH", "") 1779 tg.tempDir("home") 1780 tg.setenv(homeEnvName(), tg.path("home")) 1781 1782 tg.runFail("install", "github.com/golang/example/hello") 1783 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH") 1784 } 1785 1786 // Issue 4186. go get cannot be used to download packages to $GOROOT. 1787 // Test that without GOPATH set, go get should fail. 1788 func TestGoGetIntoGOROOT(t *testing.T) { 1789 testenv.MustHaveExternalNetwork(t) 1790 1791 tg := testgo(t) 1792 defer tg.cleanup() 1793 tg.parallel() 1794 tg.tempDir("src") 1795 1796 // Fails because GOROOT=GOPATH 1797 tg.setenv("GOPATH", tg.path(".")) 1798 tg.setenv("GOROOT", tg.path(".")) 1799 tg.runFail("get", "-d", "github.com/golang/example/hello") 1800 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT") 1801 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT") 1802 1803 // Fails because GOROOT=GOPATH after cleaning. 1804 tg.setenv("GOPATH", tg.path(".")+"/") 1805 tg.setenv("GOROOT", tg.path(".")) 1806 tg.runFail("get", "-d", "github.com/golang/example/hello") 1807 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT") 1808 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT") 1809 1810 tg.setenv("GOPATH", tg.path(".")) 1811 tg.setenv("GOROOT", tg.path(".")+"/") 1812 tg.runFail("get", "-d", "github.com/golang/example/hello") 1813 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT") 1814 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT") 1815 1816 // Fails because GOROOT=$HOME/go so default GOPATH unset. 1817 tg.tempDir("home/go") 1818 tg.setenv(homeEnvName(), tg.path("home")) 1819 tg.setenv("GOPATH", "") 1820 tg.setenv("GOROOT", tg.path("home/go")) 1821 tg.runFail("get", "-d", "github.com/golang/example/hello") 1822 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set") 1823 1824 tg.setenv(homeEnvName(), tg.path("home")+"/") 1825 tg.setenv("GOPATH", "") 1826 tg.setenv("GOROOT", tg.path("home/go")) 1827 tg.runFail("get", "-d", "github.com/golang/example/hello") 1828 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set") 1829 1830 tg.setenv(homeEnvName(), tg.path("home")) 1831 tg.setenv("GOPATH", "") 1832 tg.setenv("GOROOT", tg.path("home/go")+"/") 1833 tg.runFail("get", "-d", "github.com/golang/example/hello") 1834 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set") 1835 } 1836 1837 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) { 1838 tg := testgo(t) 1839 defer tg.cleanup() 1840 tg.parallel() 1841 tg.tempFile("main.go", `package main 1842 var extern string 1843 func main() { 1844 println(extern) 1845 }`) 1846 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go")) 1847 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`) 1848 } 1849 1850 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) { 1851 tg := testgo(t) 1852 defer tg.cleanup() 1853 // TODO: tg.parallel() 1854 tg.makeTempdir() 1855 tg.cd(tg.path(".")) 1856 tg.run("test", "-cpuprofile", "errors.prof", "errors") 1857 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test") 1858 } 1859 1860 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) { 1861 tg := testgo(t) 1862 defer tg.cleanup() 1863 // TODO: tg.parallel() 1864 tg.makeTempdir() 1865 tg.cd(tg.path(".")) 1866 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors") 1867 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test") 1868 } 1869 1870 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) { 1871 tg := testgo(t) 1872 defer tg.cleanup() 1873 // TODO: tg.parallel() 1874 tg.makeTempdir() 1875 tg.cd(tg.path(".")) 1876 tg.run("test", "-mutexprofile", "errors.prof", "errors") 1877 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test") 1878 } 1879 1880 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) { 1881 tg := testgo(t) 1882 defer tg.cleanup() 1883 // TODO: tg.parallel() 1884 tg.makeTempdir() 1885 tg.cd(tg.path(".")) 1886 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors") 1887 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test") 1888 } 1889 1890 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) { 1891 tg := testgo(t) 1892 defer tg.cleanup() 1893 tg.parallel() 1894 tg.makeTempdir() 1895 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1896 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test") 1897 } 1898 1899 func TestGoTestDashOWritesBinary(t *testing.T) { 1900 tg := testgo(t) 1901 defer tg.cleanup() 1902 tg.parallel() 1903 tg.makeTempdir() 1904 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1905 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test") 1906 } 1907 1908 func TestGoTestDashIDashOWritesBinary(t *testing.T) { 1909 tg := testgo(t) 1910 defer tg.cleanup() 1911 tg.parallel() 1912 tg.makeTempdir() 1913 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1914 tg.grepBothNot("PASS|FAIL", "test should not have run") 1915 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test") 1916 } 1917 1918 // Issue 4568. 1919 func TestSymlinksList(t *testing.T) { 1920 testenv.MustHaveSymlink(t) 1921 1922 tg := testgo(t) 1923 defer tg.cleanup() 1924 // TODO: tg.parallel() 1925 tg.tempDir("src") 1926 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1"))) 1927 tg.tempFile("src/dir1/p.go", "package p") 1928 tg.setenv("GOPATH", tg.path(".")) 1929 tg.cd(tg.path("src")) 1930 tg.run("list", "-f", "{{.Root}}", "dir1") 1931 if strings.TrimSpace(tg.getStdout()) != tg.path(".") { 1932 t.Error("confused by symlinks") 1933 } 1934 } 1935 1936 // Issue 14054. 1937 func TestSymlinksVendor(t *testing.T) { 1938 testenv.MustHaveSymlink(t) 1939 1940 tg := testgo(t) 1941 defer tg.cleanup() 1942 // TODO: tg.parallel() 1943 tg.tempDir("gopath/src/dir1/vendor/v") 1944 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}") 1945 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v") 1946 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1"))) 1947 tg.setenv("GOPATH", tg.path("gopath")) 1948 tg.cd(tg.path("symdir1")) 1949 tg.run("list", "-f", "{{.Root}}", ".") 1950 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") { 1951 t.Error("list confused by symlinks") 1952 } 1953 1954 // All of these should succeed, not die in vendor-handling code. 1955 tg.run("run", "p.go") 1956 tg.run("build") 1957 tg.run("install") 1958 } 1959 1960 // Issue 15201. 1961 func TestSymlinksVendor15201(t *testing.T) { 1962 testenv.MustHaveSymlink(t) 1963 1964 tg := testgo(t) 1965 defer tg.cleanup() 1966 1967 tg.tempDir("gopath/src/x/y/_vendor/src/x") 1968 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y"))) 1969 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n") 1970 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor"))) 1971 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n") 1972 1973 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath")) 1974 tg.cd(tg.path("gopath/src")) 1975 tg.run("list", "./...") 1976 } 1977 1978 func TestSymlinksInternal(t *testing.T) { 1979 testenv.MustHaveSymlink(t) 1980 1981 tg := testgo(t) 1982 defer tg.cleanup() 1983 tg.tempDir("gopath/src/dir1/internal/v") 1984 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}") 1985 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v") 1986 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1"))) 1987 tg.setenv("GOPATH", tg.path("gopath")) 1988 tg.cd(tg.path("symdir1")) 1989 tg.run("list", "-f", "{{.Root}}", ".") 1990 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") { 1991 t.Error("list confused by symlinks") 1992 } 1993 1994 // All of these should succeed, not die in internal-handling code. 1995 tg.run("run", "p.go") 1996 tg.run("build") 1997 tg.run("install") 1998 } 1999 2000 // Issue 4515. 2001 func TestInstallWithTags(t *testing.T) { 2002 tg := testgo(t) 2003 defer tg.cleanup() 2004 tg.parallel() 2005 tg.tempDir("bin") 2006 tg.tempFile("src/example/a/main.go", `package main 2007 func main() {}`) 2008 tg.tempFile("src/example/b/main.go", `// +build mytag 2009 2010 package main 2011 func main() {}`) 2012 tg.setenv("GOPATH", tg.path(".")) 2013 tg.run("install", "-tags", "mytag", "example/a", "example/b") 2014 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries") 2015 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries") 2016 tg.must(os.Remove(tg.path("bin/a" + exeSuffix))) 2017 tg.must(os.Remove(tg.path("bin/b" + exeSuffix))) 2018 tg.run("install", "-tags", "mytag", "example/...") 2019 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries") 2020 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries") 2021 tg.run("list", "-tags", "mytag", "example/b...") 2022 if strings.TrimSpace(tg.getStdout()) != "example/b" { 2023 t.Error("go list example/b did not find example/b") 2024 } 2025 } 2026 2027 // Issue 4773 2028 func TestCaseCollisions(t *testing.T) { 2029 tg := testgo(t) 2030 defer tg.cleanup() 2031 tg.parallel() 2032 tg.tempDir("src/example/a/pkg") 2033 tg.tempDir("src/example/a/Pkg") 2034 tg.tempDir("src/example/b") 2035 tg.setenv("GOPATH", tg.path(".")) 2036 tg.tempFile("src/example/a/a.go", `package p 2037 import ( 2038 _ "example/a/pkg" 2039 _ "example/a/Pkg" 2040 )`) 2041 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`) 2042 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`) 2043 tg.run("list", "-json", "example/a") 2044 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision") 2045 tg.runFail("build", "example/a") 2046 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision") 2047 tg.tempFile("src/example/b/file.go", `package b`) 2048 tg.tempFile("src/example/b/FILE.go", `package b`) 2049 f, err := os.Open(tg.path("src/example/b")) 2050 tg.must(err) 2051 names, err := f.Readdirnames(0) 2052 tg.must(err) 2053 tg.check(f.Close()) 2054 args := []string{"list"} 2055 if len(names) == 2 { 2056 // case-sensitive file system, let directory read find both files 2057 args = append(args, "example/b") 2058 } else { 2059 // case-insensitive file system, list files explicitly on command line 2060 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go")) 2061 } 2062 tg.runFail(args...) 2063 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision") 2064 2065 tg.runFail("list", "example/a/pkg", "example/a/Pkg") 2066 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision") 2067 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg") 2068 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision") 2069 tg.runFail("build", "example/a/pkg", "example/a/Pkg") 2070 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision") 2071 } 2072 2073 // Issue 17451, 17662. 2074 func TestSymlinkWarning(t *testing.T) { 2075 tg := testgo(t) 2076 defer tg.cleanup() 2077 tg.parallel() 2078 tg.makeTempdir() 2079 tg.setenv("GOPATH", tg.path(".")) 2080 2081 tg.tempDir("src/example/xx") 2082 tg.tempDir("yy/zz") 2083 tg.tempFile("yy/zz/zz.go", "package zz\n") 2084 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil { 2085 t.Skip("symlink failed: %v", err) 2086 } 2087 tg.run("list", "example/xx/z...") 2088 tg.grepStdoutNot(".", "list should not have matched anything") 2089 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages") 2090 tg.grepStderrNot("symlink", "list should not have reported symlink") 2091 2092 tg.run("list", "example/xx/...") 2093 tg.grepStdoutNot(".", "list should not have matched anything") 2094 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages") 2095 tg.grepStderr("ignoring symlink", "list should have reported symlink") 2096 } 2097 2098 // Issue 8181. 2099 func TestGoGetDashTIssue8181(t *testing.T) { 2100 testenv.MustHaveExternalNetwork(t) 2101 2102 tg := testgo(t) 2103 defer tg.cleanup() 2104 tg.parallel() 2105 tg.makeTempdir() 2106 tg.setenv("GOPATH", tg.path(".")) 2107 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b") 2108 tg.run("list", "...") 2109 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit") 2110 } 2111 2112 func TestIssue11307(t *testing.T) { 2113 // go get -u was not working except in checkout directory 2114 testenv.MustHaveExternalNetwork(t) 2115 2116 tg := testgo(t) 2117 defer tg.cleanup() 2118 tg.parallel() 2119 tg.makeTempdir() 2120 tg.setenv("GOPATH", tg.path(".")) 2121 tg.run("get", "github.com/rsc/go-get-issue-11307") 2122 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing 2123 } 2124 2125 func TestShadowingLogic(t *testing.T) { 2126 tg := testgo(t) 2127 defer tg.cleanup() 2128 pwd := tg.pwd() 2129 sep := string(filepath.ListSeparator) 2130 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2")) 2131 2132 // The math in root1 is not "math" because the standard math is. 2133 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math") 2134 pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1) 2135 if !strings.HasPrefix(pwdForwardSlash, "/") { 2136 pwdForwardSlash = "/" + pwdForwardSlash 2137 } 2138 // The output will have makeImportValid applies, but we only 2139 // bother to deal with characters we might reasonably see. 2140 for _, r := range " :" { 2141 pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1) 2142 } 2143 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")" 2144 if strings.TrimSpace(tg.getStdout()) != want { 2145 t.Error("shadowed math is not shadowed; looking for", want) 2146 } 2147 2148 // The foo in root1 is "foo". 2149 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo") 2150 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" { 2151 t.Error("unshadowed foo is shadowed") 2152 } 2153 2154 // The foo in root2 is not "foo" because the foo in root1 got there first. 2155 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo") 2156 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")" 2157 if strings.TrimSpace(tg.getStdout()) != want { 2158 t.Error("shadowed foo is not shadowed; looking for", want) 2159 } 2160 2161 // The error for go install should mention the conflicting directory. 2162 tg.runFail("install", "./testdata/shadow/root2/src/foo") 2163 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") 2164 if strings.TrimSpace(tg.getStderr()) != want { 2165 t.Error("wrong shadowed install error; looking for", want) 2166 } 2167 } 2168 2169 // Only succeeds if source order is preserved. 2170 func TestSourceFileNameOrderPreserved(t *testing.T) { 2171 tg := testgo(t) 2172 defer tg.cleanup() 2173 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go") 2174 } 2175 2176 // Check that coverage analysis works at all. 2177 // Don't worry about the exact numbers but require not 0.0%. 2178 func checkCoverage(tg *testgoData, data string) { 2179 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) { 2180 tg.t.Error("some coverage results are 0.0%") 2181 } 2182 tg.t.Log(data) 2183 } 2184 2185 func TestCoverageRuns(t *testing.T) { 2186 if testing.Short() { 2187 t.Skip("don't build libraries for coverage in short mode") 2188 } 2189 tg := testgo(t) 2190 defer tg.cleanup() 2191 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp") 2192 data := tg.getStdout() + tg.getStderr() 2193 tg.run("test", "-short", "-cover", "strings", "math", "regexp") 2194 data += tg.getStdout() + tg.getStderr() 2195 checkCoverage(tg, data) 2196 } 2197 2198 // Check that coverage analysis uses set mode. 2199 func TestCoverageUsesSetMode(t *testing.T) { 2200 if testing.Short() { 2201 t.Skip("don't build libraries for coverage in short mode") 2202 } 2203 tg := testgo(t) 2204 defer tg.cleanup() 2205 tg.creatingTemp("testdata/cover.out") 2206 tg.run("test", "-short", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out") 2207 data := tg.getStdout() + tg.getStderr() 2208 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil { 2209 t.Error(err) 2210 } else { 2211 if !bytes.Contains(out, []byte("mode: set")) { 2212 t.Error("missing mode: set") 2213 } 2214 } 2215 checkCoverage(tg, data) 2216 } 2217 2218 func TestCoverageUsesAtomicModeForRace(t *testing.T) { 2219 if testing.Short() { 2220 t.Skip("don't build libraries for coverage in short mode") 2221 } 2222 if !canRace { 2223 t.Skip("skipping because race detector not supported") 2224 } 2225 2226 tg := testgo(t) 2227 defer tg.cleanup() 2228 tg.creatingTemp("testdata/cover.out") 2229 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out") 2230 data := tg.getStdout() + tg.getStderr() 2231 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil { 2232 t.Error(err) 2233 } else { 2234 if !bytes.Contains(out, []byte("mode: atomic")) { 2235 t.Error("missing mode: atomic") 2236 } 2237 } 2238 checkCoverage(tg, data) 2239 } 2240 2241 func TestCoverageImportMainLoop(t *testing.T) { 2242 tg := testgo(t) 2243 defer tg.cleanup() 2244 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2245 tg.runFail("test", "importmain/test") 2246 tg.grepStderr("not an importable package", "did not detect import main") 2247 tg.runFail("test", "-cover", "importmain/test") 2248 tg.grepStderr("not an importable package", "did not detect import main") 2249 } 2250 2251 func TestPluginNonMain(t *testing.T) { 2252 wd, err := os.Getwd() 2253 if err != nil { 2254 t.Fatal(err) 2255 } 2256 2257 pkg := filepath.Join(wd, "testdata", "testdep", "p2") 2258 2259 tg := testgo(t) 2260 defer tg.cleanup() 2261 2262 tg.runFail("build", "-buildmode=plugin", pkg) 2263 } 2264 2265 func TestTestEmpty(t *testing.T) { 2266 if !canRace { 2267 t.Skip("no race detector") 2268 } 2269 2270 wd, _ := os.Getwd() 2271 testdata := filepath.Join(wd, "testdata") 2272 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} { 2273 t.Run(dir, func(t *testing.T) { 2274 tg := testgo(t) 2275 defer tg.cleanup() 2276 tg.setenv("GOPATH", testdata) 2277 tg.cd(filepath.Join(testdata, "src/empty/"+dir)) 2278 tg.run("test", "-cover", "-coverpkg=.", "-race") 2279 }) 2280 if testing.Short() { 2281 break 2282 } 2283 } 2284 } 2285 2286 func TestNoGoError(t *testing.T) { 2287 wd, _ := os.Getwd() 2288 testdata := filepath.Join(wd, "testdata") 2289 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} { 2290 t.Run(dir, func(t *testing.T) { 2291 tg := testgo(t) 2292 defer tg.cleanup() 2293 tg.setenv("GOPATH", testdata) 2294 tg.cd(filepath.Join(testdata, "src")) 2295 tg.runFail("build", "./"+dir) 2296 var want string 2297 if strings.Contains(dir, "test") { 2298 want = "no non-test Go files in " 2299 } else if dir == "exclude" { 2300 want = "build constraints exclude all Go files in " 2301 } else { 2302 want = "no Go files in " 2303 } 2304 tg.grepStderr(want, "wrong reason for failure") 2305 }) 2306 } 2307 } 2308 2309 func TestTestRaceInstall(t *testing.T) { 2310 if !canRace { 2311 t.Skip("no race detector") 2312 } 2313 if testing.Short() && testenv.Builder() == "" { 2314 t.Skip("don't rebuild the standard library in short mode") 2315 } 2316 2317 tg := testgo(t) 2318 defer tg.cleanup() 2319 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2320 2321 tg.tempDir("pkg") 2322 pkgdir := tg.path("pkg") 2323 tg.run("install", "-race", "-pkgdir="+pkgdir, "std") 2324 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg") 2325 if tg.getStderr() != "" { 2326 t.Error("go test -i -race: rebuilds cached packages") 2327 } 2328 } 2329 2330 func TestBuildDryRunWithCgo(t *testing.T) { 2331 if !canCgo { 2332 t.Skip("skipping because cgo not enabled") 2333 } 2334 2335 tg := testgo(t) 2336 defer tg.cleanup() 2337 tg.tempFile("foo.go", `package main 2338 2339 /* 2340 #include <limits.h> 2341 */ 2342 import "C" 2343 2344 func main() { 2345 println(C.INT_MAX) 2346 }`) 2347 tg.run("build", "-n", tg.path("foo.go")) 2348 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file") 2349 } 2350 2351 func TestCoverageWithCgo(t *testing.T) { 2352 if !canCgo { 2353 t.Skip("skipping because cgo not enabled") 2354 } 2355 2356 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} { 2357 t.Run(dir, func(t *testing.T) { 2358 tg := testgo(t) 2359 tg.parallel() 2360 defer tg.cleanup() 2361 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2362 tg.run("test", "-short", "-cover", dir) 2363 data := tg.getStdout() + tg.getStderr() 2364 checkCoverage(tg, data) 2365 }) 2366 } 2367 } 2368 2369 func TestCgoAsmError(t *testing.T) { 2370 if !canCgo { 2371 t.Skip("skipping because cgo not enabled") 2372 } 2373 2374 tg := testgo(t) 2375 tg.parallel() 2376 defer tg.cleanup() 2377 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2378 tg.runFail("build", "cgoasm") 2379 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file") 2380 } 2381 2382 func TestCgoDependsOnSyscall(t *testing.T) { 2383 if testing.Short() { 2384 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode") 2385 } 2386 if !canCgo { 2387 t.Skip("skipping because cgo not enabled") 2388 } 2389 if !canRace { 2390 t.Skip("skipping because race detector not supported") 2391 } 2392 2393 tg := testgo(t) 2394 defer tg.cleanup() 2395 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race")) 2396 tg.must(err) 2397 for _, file := range files { 2398 tg.check(os.RemoveAll(file)) 2399 } 2400 tg.tempFile("src/foo/foo.go", ` 2401 package foo 2402 //#include <stdio.h> 2403 import "C"`) 2404 tg.setenv("GOPATH", tg.path(".")) 2405 tg.run("build", "-race", "foo") 2406 } 2407 2408 func TestCgoShowsFullPathNames(t *testing.T) { 2409 if !canCgo { 2410 t.Skip("skipping because cgo not enabled") 2411 } 2412 2413 tg := testgo(t) 2414 defer tg.cleanup() 2415 tg.parallel() 2416 tg.tempFile("src/x/y/dirname/foo.go", ` 2417 package foo 2418 import "C" 2419 func f() {`) 2420 tg.setenv("GOPATH", tg.path(".")) 2421 tg.runFail("build", "x/y/dirname") 2422 tg.grepBoth("x/y/dirname", "error did not use full path") 2423 } 2424 2425 func TestCgoHandlesWlORIGIN(t *testing.T) { 2426 if !canCgo { 2427 t.Skip("skipping because cgo not enabled") 2428 } 2429 2430 tg := testgo(t) 2431 defer tg.cleanup() 2432 tg.parallel() 2433 tg.tempFile("src/origin/origin.go", `package origin 2434 // #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN 2435 // void f(void) {} 2436 import "C" 2437 func f() { C.f() }`) 2438 tg.setenv("GOPATH", tg.path(".")) 2439 tg.run("build", "origin") 2440 } 2441 2442 func TestCgoPkgConfig(t *testing.T) { 2443 if !canCgo { 2444 t.Skip("skipping because cgo not enabled") 2445 } 2446 tg := testgo(t) 2447 defer tg.cleanup() 2448 tg.parallel() 2449 2450 tg.run("env", "PKG_CONFIG") 2451 pkgConfig := strings.TrimSpace(tg.getStdout()) 2452 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil { 2453 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out) 2454 } 2455 2456 // OpenBSD's pkg-config is strict about whitespace and only 2457 // supports backslash-escaped whitespace. It does not support 2458 // quotes, which the normal freedesktop.org pkg-config does 2459 // support. See http://man.openbsd.org/pkg-config.1 2460 tg.tempFile("foo.pc", ` 2461 Name: foo 2462 Description: The foo library 2463 Version: 1.0.0 2464 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world 2465 `) 2466 tg.tempFile("foo.go", `package main 2467 2468 /* 2469 #cgo pkg-config: foo 2470 int value() { 2471 return DEFINED_FROM_PKG_CONFIG; 2472 } 2473 */ 2474 import "C" 2475 import "os" 2476 2477 func main() { 2478 if C.value() != 42 { 2479 println("value() =", C.value(), "wanted 42") 2480 os.Exit(1) 2481 } 2482 } 2483 `) 2484 tg.setenv("PKG_CONFIG_PATH", tg.path(".")) 2485 tg.run("run", tg.path("foo.go")) 2486 } 2487 2488 // "go test -c -test.bench=XXX errors" should not hang 2489 func TestIssue6480(t *testing.T) { 2490 tg := testgo(t) 2491 defer tg.cleanup() 2492 // TODO: tg.parallel() 2493 tg.makeTempdir() 2494 tg.cd(tg.path(".")) 2495 tg.run("test", "-c", "-test.bench=XXX", "errors") 2496 } 2497 2498 // cmd/cgo: undefined reference when linking a C-library using gccgo 2499 func TestIssue7573(t *testing.T) { 2500 if !canCgo { 2501 t.Skip("skipping because cgo not enabled") 2502 } 2503 if _, err := exec.LookPath("gccgo"); err != nil { 2504 t.Skip("skipping because no gccgo compiler found") 2505 } 2506 2507 tg := testgo(t) 2508 defer tg.cleanup() 2509 tg.parallel() 2510 tg.tempFile("src/cgoref/cgoref.go", ` 2511 package main 2512 // #cgo LDFLAGS: -L alibpath -lalib 2513 // void f(void) {} 2514 import "C" 2515 2516 func main() { C.f() }`) 2517 tg.setenv("GOPATH", tg.path(".")) 2518 tg.run("build", "-n", "-compiler", "gccgo", "cgoref") 2519 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`) 2520 } 2521 2522 func TestListTemplateContextFunction(t *testing.T) { 2523 t.Parallel() 2524 for _, tt := range []struct { 2525 v string 2526 want string 2527 }{ 2528 {"GOARCH", runtime.GOARCH}, 2529 {"GOOS", runtime.GOOS}, 2530 {"GOROOT", filepath.Clean(runtime.GOROOT())}, 2531 {"GOPATH", os.Getenv("GOPATH")}, 2532 {"CgoEnabled", ""}, 2533 {"UseAllFiles", ""}, 2534 {"Compiler", ""}, 2535 {"BuildTags", ""}, 2536 {"ReleaseTags", ""}, 2537 {"InstallSuffix", ""}, 2538 } { 2539 tt := tt 2540 t.Run(tt.v, func(t *testing.T) { 2541 tg := testgo(t) 2542 tg.parallel() 2543 defer tg.cleanup() 2544 tmpl := "{{context." + tt.v + "}}" 2545 tg.run("list", "-f", tmpl) 2546 if tt.want == "" { 2547 return 2548 } 2549 if got := strings.TrimSpace(tg.getStdout()); got != tt.want { 2550 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want) 2551 } 2552 }) 2553 } 2554 } 2555 2556 // cmd/go: "go test" should fail if package does not build 2557 func TestIssue7108(t *testing.T) { 2558 tg := testgo(t) 2559 defer tg.cleanup() 2560 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2561 tg.runFail("test", "notest") 2562 } 2563 2564 // cmd/go: go test -a foo does not rebuild regexp. 2565 func TestIssue6844(t *testing.T) { 2566 if testing.Short() { 2567 t.Skip("don't rebuild the standard library in short mode") 2568 } 2569 2570 tg := testgo(t) 2571 defer tg.cleanup() 2572 tg.creatingTemp("deps.test" + exeSuffix) 2573 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go") 2574 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp") 2575 } 2576 2577 func TestBuildDashIInstallsDependencies(t *testing.T) { 2578 tg := testgo(t) 2579 defer tg.cleanup() 2580 tg.parallel() 2581 tg.tempFile("src/x/y/foo/foo.go", `package foo 2582 func F() {}`) 2583 tg.tempFile("src/x/y/bar/bar.go", `package bar 2584 import "x/y/foo" 2585 func F() { foo.F() }`) 2586 tg.setenv("GOPATH", tg.path(".")) 2587 2588 checkbar := func(desc string) { 2589 tg.sleep() 2590 tg.must(os.Chtimes(tg.path("src/x/y/foo/foo.go"), time.Now(), time.Now())) 2591 tg.sleep() 2592 tg.run("build", "-v", "-i", "x/y/bar") 2593 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo") 2594 tg.run("build", "-v", "-i", "x/y/bar") 2595 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo") 2596 } 2597 checkbar("pkg") 2598 tg.creatingTemp("bar" + exeSuffix) 2599 tg.tempFile("src/x/y/bar/bar.go", `package main 2600 import "x/y/foo" 2601 func main() { foo.F() }`) 2602 checkbar("cmd") 2603 } 2604 2605 func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) { 2606 tg := testgo(t) 2607 defer tg.cleanup() 2608 tg.runFail("build", "./testdata/testonly") 2609 tg.grepStderr("no non-test Go files in", "go build ./testdata/testonly produced unexpected error") 2610 } 2611 2612 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) { 2613 tg := testgo(t) 2614 defer tg.cleanup() 2615 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2616 tg.runFail("test", "-c", "testcycle/p3") 2617 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error") 2618 2619 tg.runFail("test", "-c", "testcycle/q1") 2620 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error") 2621 } 2622 2623 func TestGoTestFooTestWorks(t *testing.T) { 2624 tg := testgo(t) 2625 defer tg.cleanup() 2626 tg.run("test", "testdata/standalone_test.go") 2627 } 2628 2629 func TestGoTestFlagsAfterPackage(t *testing.T) { 2630 tg := testgo(t) 2631 defer tg.cleanup() 2632 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags. 2633 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags. 2634 } 2635 2636 func TestGoTestXtestonlyWorks(t *testing.T) { 2637 tg := testgo(t) 2638 defer tg.cleanup() 2639 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2640 tg.run("clean", "-i", "xtestonly") 2641 tg.run("test", "xtestonly") 2642 } 2643 2644 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) { 2645 tg := testgo(t) 2646 defer tg.cleanup() 2647 tg.run("test", "-v", "./testdata/norunexample") 2648 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built") 2649 } 2650 2651 func TestGoGenerateHandlesSimpleCommand(t *testing.T) { 2652 if runtime.GOOS == "windows" { 2653 t.Skip("skipping because windows has no echo command") 2654 } 2655 2656 tg := testgo(t) 2657 defer tg.cleanup() 2658 tg.run("generate", "./testdata/generate/test1.go") 2659 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output") 2660 } 2661 2662 func TestGoGenerateHandlesCommandAlias(t *testing.T) { 2663 if runtime.GOOS == "windows" { 2664 t.Skip("skipping because windows has no echo command") 2665 } 2666 2667 tg := testgo(t) 2668 defer tg.cleanup() 2669 tg.run("generate", "./testdata/generate/test2.go") 2670 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output") 2671 } 2672 2673 func TestGoGenerateVariableSubstitution(t *testing.T) { 2674 if runtime.GOOS == "windows" { 2675 t.Skip("skipping because windows has no echo command") 2676 } 2677 2678 tg := testgo(t) 2679 defer tg.cleanup() 2680 tg.run("generate", "./testdata/generate/test3.go") 2681 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output") 2682 } 2683 2684 func TestGoGenerateRunFlag(t *testing.T) { 2685 if runtime.GOOS == "windows" { 2686 t.Skip("skipping because windows has no echo command") 2687 } 2688 2689 tg := testgo(t) 2690 defer tg.cleanup() 2691 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go") 2692 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes") 2693 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no") 2694 } 2695 2696 func TestGoGenerateEnv(t *testing.T) { 2697 switch runtime.GOOS { 2698 case "plan9", "windows": 2699 t.Skipf("skipping because %s does not have the env command", runtime.GOOS) 2700 } 2701 tg := testgo(t) 2702 defer tg.cleanup() 2703 tg.parallel() 2704 tg.tempFile("env.go", "package main\n\n//go:generate env") 2705 tg.run("generate", tg.path("env.go")) 2706 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} { 2707 tg.grepStdout("^"+v+"=", "go generate environment missing "+v) 2708 } 2709 } 2710 2711 func TestGoGenerateBadImports(t *testing.T) { 2712 if runtime.GOOS == "windows" { 2713 t.Skip("skipping because windows has no echo command") 2714 } 2715 2716 // This package has an invalid import causing an import cycle, 2717 // but go generate is supposed to still run. 2718 tg := testgo(t) 2719 defer tg.cleanup() 2720 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2721 tg.run("generate", "gencycle") 2722 tg.grepStdout("hello world", "go generate gencycle did not run generator") 2723 } 2724 2725 func TestGoGetCustomDomainWildcard(t *testing.T) { 2726 testenv.MustHaveExternalNetwork(t) 2727 2728 tg := testgo(t) 2729 defer tg.cleanup() 2730 tg.makeTempdir() 2731 tg.setenv("GOPATH", tg.path(".")) 2732 tg.run("get", "-u", "rsc.io/pdf/...") 2733 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd") 2734 } 2735 2736 func TestGoGetInternalWildcard(t *testing.T) { 2737 testenv.MustHaveExternalNetwork(t) 2738 2739 tg := testgo(t) 2740 defer tg.cleanup() 2741 tg.makeTempdir() 2742 tg.setenv("GOPATH", tg.path(".")) 2743 // used to fail with errors about internal packages 2744 tg.run("get", "github.com/rsc/go-get-issue-11960/...") 2745 } 2746 2747 func TestGoVetWithExternalTests(t *testing.T) { 2748 tg := testgo(t) 2749 defer tg.cleanup() 2750 tg.makeTempdir() 2751 tg.run("install", "cmd/vet") 2752 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2753 tg.runFail("vet", "vetpkg") 2754 tg.grepBoth("missing argument for Printf", "go vet vetpkg did not find missing argument for Printf") 2755 } 2756 2757 func TestGoVetWithTags(t *testing.T) { 2758 tg := testgo(t) 2759 defer tg.cleanup() 2760 tg.makeTempdir() 2761 tg.run("install", "cmd/vet") 2762 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2763 tg.runFail("vet", "-tags", "tagtest", "vetpkg") 2764 tg.grepBoth(`c\.go.*wrong number of args for format`, "go vet vetpkg did not run scan tagged file") 2765 } 2766 2767 func TestGoVetWithFlagsOn(t *testing.T) { 2768 tg := testgo(t) 2769 defer tg.cleanup() 2770 tg.makeTempdir() 2771 tg.run("install", "cmd/vet") 2772 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2773 tg.runFail("vet", "-printf", "vetpkg") 2774 tg.grepBoth("missing argument for Printf", "go vet -printf vetpkg did not find missing argument for Printf") 2775 } 2776 2777 func TestGoVetWithFlagsOff(t *testing.T) { 2778 tg := testgo(t) 2779 defer tg.cleanup() 2780 tg.makeTempdir() 2781 tg.run("install", "cmd/vet") 2782 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2783 tg.run("vet", "-printf=false", "vetpkg") 2784 } 2785 2786 // Issue 9767, 19769. 2787 func TestGoGetDotSlashDownload(t *testing.T) { 2788 testenv.MustHaveExternalNetwork(t) 2789 2790 tg := testgo(t) 2791 defer tg.cleanup() 2792 tg.tempDir("src/rsc.io") 2793 tg.setenv("GOPATH", tg.path(".")) 2794 tg.cd(tg.path("src/rsc.io")) 2795 tg.run("get", "./pprof_mac_fix") 2796 } 2797 2798 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS 2799 func TestGoGetHTTPS404(t *testing.T) { 2800 testenv.MustHaveExternalNetwork(t) 2801 switch runtime.GOOS { 2802 case "darwin", "linux", "freebsd": 2803 default: 2804 t.Skipf("test case does not work on %s", runtime.GOOS) 2805 } 2806 2807 tg := testgo(t) 2808 defer tg.cleanup() 2809 tg.tempDir("src") 2810 tg.setenv("GOPATH", tg.path(".")) 2811 tg.run("get", "bazil.org/fuse/fs/fstestutil") 2812 } 2813 2814 // Test that you cannot import a main package. 2815 // See golang.org/issue/4210 and golang.org/issue/17475. 2816 func TestImportMain(t *testing.T) { 2817 tg := testgo(t) 2818 tg.parallel() 2819 defer tg.cleanup() 2820 2821 // Importing package main from that package main's test should work. 2822 tg.tempFile("src/x/main.go", `package main 2823 var X int 2824 func main() {}`) 2825 tg.tempFile("src/x/main_test.go", `package main_test 2826 import xmain "x" 2827 import "testing" 2828 var _ = xmain.X 2829 func TestFoo(t *testing.T) {} 2830 `) 2831 tg.setenv("GOPATH", tg.path(".")) 2832 tg.creatingTemp("x") 2833 tg.run("build", "x") 2834 tg.run("test", "x") 2835 2836 // Importing package main from another package should fail. 2837 tg.tempFile("src/p1/p.go", `package p1 2838 import xmain "x" 2839 var _ = xmain.X 2840 `) 2841 tg.runFail("build", "p1") 2842 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2843 2844 // ... even in that package's test. 2845 tg.tempFile("src/p2/p.go", `package p2 2846 `) 2847 tg.tempFile("src/p2/p_test.go", `package p2 2848 import xmain "x" 2849 import "testing" 2850 var _ = xmain.X 2851 func TestFoo(t *testing.T) {} 2852 `) 2853 tg.run("build", "p2") 2854 tg.runFail("test", "p2") 2855 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2856 2857 // ... even if that package's test is an xtest. 2858 tg.tempFile("src/p3/p.go", `package p 2859 `) 2860 tg.tempFile("src/p3/p_test.go", `package p_test 2861 import xmain "x" 2862 import "testing" 2863 var _ = xmain.X 2864 func TestFoo(t *testing.T) {} 2865 `) 2866 tg.run("build", "p3") 2867 tg.runFail("test", "p3") 2868 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2869 2870 // ... even if that package is a package main 2871 tg.tempFile("src/p4/p.go", `package main 2872 func main() {} 2873 `) 2874 tg.tempFile("src/p4/p_test.go", `package main 2875 import xmain "x" 2876 import "testing" 2877 var _ = xmain.X 2878 func TestFoo(t *testing.T) {} 2879 `) 2880 tg.creatingTemp("p4" + exeSuffix) 2881 tg.run("build", "p4") 2882 tg.runFail("test", "p4") 2883 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2884 2885 // ... even if that package is a package main using an xtest. 2886 tg.tempFile("src/p5/p.go", `package main 2887 func main() {} 2888 `) 2889 tg.tempFile("src/p5/p_test.go", `package main_test 2890 import xmain "x" 2891 import "testing" 2892 var _ = xmain.X 2893 func TestFoo(t *testing.T) {} 2894 `) 2895 tg.creatingTemp("p5" + exeSuffix) 2896 tg.run("build", "p5") 2897 tg.runFail("test", "p5") 2898 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2899 } 2900 2901 // Test that you cannot use a local import in a package 2902 // accessed by a non-local import (found in a GOPATH/GOROOT). 2903 // See golang.org/issue/17475. 2904 func TestImportLocal(t *testing.T) { 2905 tg := testgo(t) 2906 tg.parallel() 2907 defer tg.cleanup() 2908 2909 tg.tempFile("src/dir/x/x.go", `package x 2910 var X int 2911 `) 2912 tg.setenv("GOPATH", tg.path(".")) 2913 tg.run("build", "dir/x") 2914 2915 // Ordinary import should work. 2916 tg.tempFile("src/dir/p0/p.go", `package p0 2917 import "dir/x" 2918 var _ = x.X 2919 `) 2920 tg.run("build", "dir/p0") 2921 2922 // Relative import should not. 2923 tg.tempFile("src/dir/p1/p.go", `package p1 2924 import "../x" 2925 var _ = x.X 2926 `) 2927 tg.runFail("build", "dir/p1") 2928 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2929 2930 // ... even in a test. 2931 tg.tempFile("src/dir/p2/p.go", `package p2 2932 `) 2933 tg.tempFile("src/dir/p2/p_test.go", `package p2 2934 import "../x" 2935 import "testing" 2936 var _ = x.X 2937 func TestFoo(t *testing.T) {} 2938 `) 2939 tg.run("build", "dir/p2") 2940 tg.runFail("test", "dir/p2") 2941 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2942 2943 // ... even in an xtest. 2944 tg.tempFile("src/dir/p2/p_test.go", `package p2_test 2945 import "../x" 2946 import "testing" 2947 var _ = x.X 2948 func TestFoo(t *testing.T) {} 2949 `) 2950 tg.run("build", "dir/p2") 2951 tg.runFail("test", "dir/p2") 2952 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2953 2954 // Relative import starting with ./ should not work either. 2955 tg.tempFile("src/dir/d.go", `package dir 2956 import "./x" 2957 var _ = x.X 2958 `) 2959 tg.runFail("build", "dir") 2960 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2961 2962 // ... even in a test. 2963 tg.tempFile("src/dir/d.go", `package dir 2964 `) 2965 tg.tempFile("src/dir/d_test.go", `package dir 2966 import "./x" 2967 import "testing" 2968 var _ = x.X 2969 func TestFoo(t *testing.T) {} 2970 `) 2971 tg.run("build", "dir") 2972 tg.runFail("test", "dir") 2973 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2974 2975 // ... even in an xtest. 2976 tg.tempFile("src/dir/d_test.go", `package dir_test 2977 import "./x" 2978 import "testing" 2979 var _ = x.X 2980 func TestFoo(t *testing.T) {} 2981 `) 2982 tg.run("build", "dir") 2983 tg.runFail("test", "dir") 2984 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2985 2986 // Relative import plain ".." should not work. 2987 tg.tempFile("src/dir/x/y/y.go", `package dir 2988 import ".." 2989 var _ = x.X 2990 `) 2991 tg.runFail("build", "dir/x/y") 2992 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2993 2994 // ... even in a test. 2995 tg.tempFile("src/dir/x/y/y.go", `package y 2996 `) 2997 tg.tempFile("src/dir/x/y/y_test.go", `package y 2998 import ".." 2999 import "testing" 3000 var _ = x.X 3001 func TestFoo(t *testing.T) {} 3002 `) 3003 tg.run("build", "dir/x/y") 3004 tg.runFail("test", "dir/x/y") 3005 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 3006 3007 // ... even in an x test. 3008 tg.tempFile("src/dir/x/y/y_test.go", `package y_test 3009 import ".." 3010 import "testing" 3011 var _ = x.X 3012 func TestFoo(t *testing.T) {} 3013 `) 3014 tg.run("build", "dir/x/y") 3015 tg.runFail("test", "dir/x/y") 3016 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 3017 3018 // Relative import "." should not work. 3019 tg.tempFile("src/dir/x/xx.go", `package x 3020 import "." 3021 var _ = x.X 3022 `) 3023 tg.runFail("build", "dir/x") 3024 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 3025 3026 // ... even in a test. 3027 tg.tempFile("src/dir/x/xx.go", `package x 3028 `) 3029 tg.tempFile("src/dir/x/xx_test.go", `package x 3030 import "." 3031 import "testing" 3032 var _ = x.X 3033 func TestFoo(t *testing.T) {} 3034 `) 3035 tg.run("build", "dir/x") 3036 tg.runFail("test", "dir/x") 3037 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 3038 3039 // ... even in an xtest. 3040 tg.tempFile("src/dir/x/xx.go", `package x 3041 `) 3042 tg.tempFile("src/dir/x/xx_test.go", `package x_test 3043 import "." 3044 import "testing" 3045 var _ = x.X 3046 func TestFoo(t *testing.T) {} 3047 `) 3048 tg.run("build", "dir/x") 3049 tg.runFail("test", "dir/x") 3050 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 3051 } 3052 3053 func TestGoGetInsecure(t *testing.T) { 3054 testenv.MustHaveExternalNetwork(t) 3055 3056 tg := testgo(t) 3057 defer tg.cleanup() 3058 tg.makeTempdir() 3059 tg.setenv("GOPATH", tg.path(".")) 3060 tg.failSSH() 3061 3062 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p" 3063 3064 // Try go get -d of HTTP-only repo (should fail). 3065 tg.runFail("get", "-d", repo) 3066 3067 // Try again with -insecure (should succeed). 3068 tg.run("get", "-d", "-insecure", repo) 3069 3070 // Try updating without -insecure (should fail). 3071 tg.runFail("get", "-d", "-u", "-f", repo) 3072 } 3073 3074 func TestGoGetUpdateInsecure(t *testing.T) { 3075 testenv.MustHaveExternalNetwork(t) 3076 3077 tg := testgo(t) 3078 defer tg.cleanup() 3079 tg.makeTempdir() 3080 tg.setenv("GOPATH", tg.path(".")) 3081 3082 const repo = "github.com/golang/example" 3083 3084 // Clone the repo via HTTP manually. 3085 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo)) 3086 if out, err := cmd.CombinedOutput(); err != nil { 3087 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out) 3088 } 3089 3090 // Update without -insecure should fail. 3091 // Update with -insecure should succeed. 3092 // We need -f to ignore import comments. 3093 const pkg = repo + "/hello" 3094 tg.runFail("get", "-d", "-u", "-f", pkg) 3095 tg.run("get", "-d", "-u", "-f", "-insecure", pkg) 3096 } 3097 3098 func TestGoGetInsecureCustomDomain(t *testing.T) { 3099 testenv.MustHaveExternalNetwork(t) 3100 3101 tg := testgo(t) 3102 defer tg.cleanup() 3103 tg.makeTempdir() 3104 tg.setenv("GOPATH", tg.path(".")) 3105 3106 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p" 3107 tg.runFail("get", "-d", repo) 3108 tg.run("get", "-d", "-insecure", repo) 3109 } 3110 3111 func TestGoRunDirs(t *testing.T) { 3112 tg := testgo(t) 3113 defer tg.cleanup() 3114 tg.cd("testdata/rundir") 3115 tg.runFail("run", "x.go", "sub/sub.go") 3116 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output") 3117 tg.runFail("run", "sub/sub.go", "x.go") 3118 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output") 3119 } 3120 3121 func TestGoInstallPkgdir(t *testing.T) { 3122 tg := testgo(t) 3123 tg.parallel() 3124 defer tg.cleanup() 3125 tg.makeTempdir() 3126 pkg := tg.path(".") 3127 tg.run("install", "-pkgdir", pkg, "errors") 3128 _, err := os.Stat(filepath.Join(pkg, "errors.a")) 3129 tg.must(err) 3130 _, err = os.Stat(filepath.Join(pkg, "runtime.a")) 3131 tg.must(err) 3132 } 3133 3134 func TestGoTestRaceInstallCgo(t *testing.T) { 3135 if !canRace { 3136 t.Skip("skipping because race detector not supported") 3137 } 3138 3139 // golang.org/issue/10500. 3140 // This used to install a race-enabled cgo. 3141 tg := testgo(t) 3142 defer tg.cleanup() 3143 tg.run("tool", "-n", "cgo") 3144 cgo := strings.TrimSpace(tg.stdout.String()) 3145 old, err := os.Stat(cgo) 3146 tg.must(err) 3147 tg.run("test", "-race", "-i", "runtime/race") 3148 new, err := os.Stat(cgo) 3149 tg.must(err) 3150 if !new.ModTime().Equal(old.ModTime()) { 3151 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo") 3152 } 3153 } 3154 3155 func TestGoTestRaceFailures(t *testing.T) { 3156 if !canRace { 3157 t.Skip("skipping because race detector not supported") 3158 } 3159 3160 tg := testgo(t) 3161 tg.parallel() 3162 defer tg.cleanup() 3163 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3164 3165 tg.run("test", "testrace") 3166 3167 tg.runFail("test", "-race", "testrace") 3168 tg.grepStdout("FAIL: TestRace", "TestRace did not fail") 3169 tg.grepBothNot("PASS", "something passed") 3170 3171 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".") 3172 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail") 3173 tg.grepBothNot("PASS", "something passed") 3174 } 3175 3176 func TestGoTestImportErrorStack(t *testing.T) { 3177 const out = `package testdep/p1 (test) 3178 imports testdep/p2 3179 imports testdep/p3: build constraints exclude all Go files ` 3180 3181 tg := testgo(t) 3182 defer tg.cleanup() 3183 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3184 tg.runFail("test", "testdep/p1") 3185 if !strings.Contains(tg.stderr.String(), out) { 3186 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String()) 3187 } 3188 } 3189 3190 func TestGoGetUpdate(t *testing.T) { 3191 // golang.org/issue/9224. 3192 // The recursive updating was trying to walk to 3193 // former dependencies, not current ones. 3194 3195 testenv.MustHaveExternalNetwork(t) 3196 3197 tg := testgo(t) 3198 defer tg.cleanup() 3199 tg.makeTempdir() 3200 tg.setenv("GOPATH", tg.path(".")) 3201 3202 rewind := func() { 3203 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd") 3204 cmd := exec.Command("git", "reset", "--hard", "HEAD~") 3205 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib") 3206 out, err := cmd.CombinedOutput() 3207 if err != nil { 3208 t.Fatalf("git: %v\n%s", err, out) 3209 } 3210 } 3211 3212 rewind() 3213 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd") 3214 3215 // Again with -d -u. 3216 rewind() 3217 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd") 3218 } 3219 3220 // Issue #20512. 3221 func TestGoGetRace(t *testing.T) { 3222 testenv.MustHaveExternalNetwork(t) 3223 if !canRace { 3224 t.Skip("skipping because race detector not supported") 3225 } 3226 3227 tg := testgo(t) 3228 defer tg.cleanup() 3229 tg.makeTempdir() 3230 tg.setenv("GOPATH", tg.path(".")) 3231 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd") 3232 } 3233 3234 func TestGoGetDomainRoot(t *testing.T) { 3235 // golang.org/issue/9357. 3236 // go get foo.io (not foo.io/subdir) was not working consistently. 3237 3238 testenv.MustHaveExternalNetwork(t) 3239 3240 tg := testgo(t) 3241 defer tg.cleanup() 3242 tg.makeTempdir() 3243 tg.setenv("GOPATH", tg.path(".")) 3244 3245 // go-get-issue-9357.appspot.com is running 3246 // the code at github.com/rsc/go-get-issue-9357, 3247 // a trivial Go on App Engine app that serves a 3248 // <meta> tag for the domain root. 3249 tg.run("get", "-d", "go-get-issue-9357.appspot.com") 3250 tg.run("get", "go-get-issue-9357.appspot.com") 3251 tg.run("get", "-u", "go-get-issue-9357.appspot.com") 3252 3253 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com"))) 3254 tg.run("get", "go-get-issue-9357.appspot.com") 3255 3256 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com"))) 3257 tg.run("get", "-u", "go-get-issue-9357.appspot.com") 3258 } 3259 3260 func TestGoInstallShadowedGOPATH(t *testing.T) { 3261 // golang.org/issue/3652. 3262 // go get foo.io (not foo.io/subdir) was not working consistently. 3263 3264 testenv.MustHaveExternalNetwork(t) 3265 3266 tg := testgo(t) 3267 defer tg.cleanup() 3268 tg.makeTempdir() 3269 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2")) 3270 3271 tg.tempDir("gopath1/src/test") 3272 tg.tempDir("gopath2/src/test") 3273 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n") 3274 3275 tg.cd(tg.path("gopath2/src/test")) 3276 tg.runFail("install") 3277 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error") 3278 } 3279 3280 func TestGoBuildGOPATHOrder(t *testing.T) { 3281 // golang.org/issue/14176#issuecomment-179895769 3282 // golang.org/issue/14192 3283 // -I arguments to compiler could end up not in GOPATH order, 3284 // leading to unexpected import resolution in the compiler. 3285 // This is still not a complete fix (see golang.org/issue/14271 and next test) 3286 // but it is clearly OK and enough to fix both of the two reported 3287 // instances of the underlying problem. It will have to do for now. 3288 3289 tg := testgo(t) 3290 defer tg.cleanup() 3291 tg.makeTempdir() 3292 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2")) 3293 3294 tg.tempFile("p1/src/foo/foo.go", "package foo\n") 3295 tg.tempFile("p2/src/baz/baz.go", "package baz\n") 3296 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n") 3297 tg.tempFile("p1/src/bar/bar.go", ` 3298 package bar 3299 import _ "baz" 3300 import _ "foo" 3301 `) 3302 3303 tg.run("install", "-x", "bar") 3304 } 3305 3306 func TestGoBuildGOPATHOrderBroken(t *testing.T) { 3307 // This test is known not to work. 3308 // See golang.org/issue/14271. 3309 t.Skip("golang.org/issue/14271") 3310 3311 tg := testgo(t) 3312 defer tg.cleanup() 3313 tg.makeTempdir() 3314 3315 tg.tempFile("p1/src/foo/foo.go", "package foo\n") 3316 tg.tempFile("p2/src/baz/baz.go", "package baz\n") 3317 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n") 3318 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n") 3319 tg.tempFile("p1/src/bar/bar.go", ` 3320 package bar 3321 import _ "baz" 3322 import _ "foo" 3323 `) 3324 3325 colon := string(filepath.ListSeparator) 3326 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2")) 3327 tg.run("install", "-x", "bar") 3328 3329 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1")) 3330 tg.run("install", "-x", "bar") 3331 } 3332 3333 func TestIssue11709(t *testing.T) { 3334 tg := testgo(t) 3335 defer tg.cleanup() 3336 tg.tempFile("run.go", ` 3337 package main 3338 import "os" 3339 func main() { 3340 if os.Getenv("TERM") != "" { 3341 os.Exit(1) 3342 } 3343 }`) 3344 tg.unsetenv("TERM") 3345 tg.run("run", tg.path("run.go")) 3346 } 3347 3348 func TestIssue12096(t *testing.T) { 3349 tg := testgo(t) 3350 defer tg.cleanup() 3351 tg.tempFile("test_test.go", ` 3352 package main 3353 import ("os"; "testing") 3354 func TestEnv(t *testing.T) { 3355 if os.Getenv("TERM") != "" { 3356 t.Fatal("TERM is set") 3357 } 3358 }`) 3359 tg.unsetenv("TERM") 3360 tg.run("test", tg.path("test_test.go")) 3361 } 3362 3363 func TestGoBuildOutput(t *testing.T) { 3364 tg := testgo(t) 3365 defer tg.cleanup() 3366 3367 tg.makeTempdir() 3368 tg.cd(tg.path(".")) 3369 3370 nonExeSuffix := ".exe" 3371 if exeSuffix == ".exe" { 3372 nonExeSuffix = "" 3373 } 3374 3375 tg.tempFile("x.go", "package main\nfunc main(){}\n") 3376 tg.run("build", "x.go") 3377 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix) 3378 tg.must(os.Remove(tg.path("x" + exeSuffix))) 3379 tg.mustNotExist("x" + nonExeSuffix) 3380 3381 tg.run("build", "-o", "myprog", "x.go") 3382 tg.mustNotExist("x") 3383 tg.mustNotExist("x.exe") 3384 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog") 3385 tg.mustNotExist("myprog.exe") 3386 3387 tg.tempFile("p.go", "package p\n") 3388 tg.run("build", "p.go") 3389 tg.mustNotExist("p") 3390 tg.mustNotExist("p.a") 3391 tg.mustNotExist("p.o") 3392 tg.mustNotExist("p.exe") 3393 3394 tg.run("build", "-o", "p.a", "p.go") 3395 tg.wantArchive("p.a") 3396 3397 tg.run("build", "cmd/gofmt") 3398 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix) 3399 tg.must(os.Remove(tg.path("gofmt" + exeSuffix))) 3400 tg.mustNotExist("gofmt" + nonExeSuffix) 3401 3402 tg.run("build", "-o", "mygofmt", "cmd/gofmt") 3403 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt") 3404 tg.mustNotExist("mygofmt.exe") 3405 tg.mustNotExist("gofmt") 3406 tg.mustNotExist("gofmt.exe") 3407 3408 tg.run("build", "sync/atomic") 3409 tg.mustNotExist("atomic") 3410 tg.mustNotExist("atomic.exe") 3411 3412 tg.run("build", "-o", "myatomic.a", "sync/atomic") 3413 tg.wantArchive("myatomic.a") 3414 tg.mustNotExist("atomic") 3415 tg.mustNotExist("atomic.a") 3416 tg.mustNotExist("atomic.exe") 3417 3418 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic") 3419 tg.grepStderr("multiple packages", "did not reject -o with multiple packages") 3420 } 3421 3422 func TestGoBuildARM(t *testing.T) { 3423 if testing.Short() { 3424 t.Skip("skipping cross-compile in short mode") 3425 } 3426 3427 tg := testgo(t) 3428 defer tg.cleanup() 3429 3430 tg.makeTempdir() 3431 tg.cd(tg.path(".")) 3432 3433 tg.setenv("GOARCH", "arm") 3434 tg.setenv("GOOS", "linux") 3435 tg.setenv("GOARM", "5") 3436 tg.tempFile("hello.go", `package main 3437 func main() {}`) 3438 tg.run("build", "hello.go") 3439 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly") 3440 } 3441 3442 func TestIssue13655(t *testing.T) { 3443 tg := testgo(t) 3444 defer tg.cleanup() 3445 for _, pkg := range []string{"runtime", "runtime/internal/atomic"} { 3446 tg.run("list", "-f", "{{.Deps}}", pkg) 3447 tg.grepStdout("runtime/internal/sys", "did not find required dependency of "+pkg+" on runtime/internal/sys") 3448 } 3449 } 3450 3451 // For issue 14337. 3452 func TestParallelTest(t *testing.T) { 3453 tg := testgo(t) 3454 tg.parallel() 3455 defer tg.cleanup() 3456 tg.makeTempdir() 3457 const testSrc = `package package_test 3458 import ( 3459 "testing" 3460 ) 3461 func TestTest(t *testing.T) { 3462 }` 3463 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1)) 3464 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1)) 3465 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1)) 3466 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1)) 3467 tg.setenv("GOPATH", tg.path(".")) 3468 tg.run("test", "-p=4", "p1", "p2", "p3", "p4") 3469 } 3470 3471 func TestCgoConsistentResults(t *testing.T) { 3472 if !canCgo { 3473 t.Skip("skipping because cgo not enabled") 3474 } 3475 switch runtime.GOOS { 3476 case "freebsd": 3477 testenv.SkipFlaky(t, 15405) 3478 case "solaris": 3479 testenv.SkipFlaky(t, 13247) 3480 } 3481 3482 tg := testgo(t) 3483 defer tg.cleanup() 3484 tg.parallel() 3485 tg.makeTempdir() 3486 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3487 exe1 := tg.path("cgotest1" + exeSuffix) 3488 exe2 := tg.path("cgotest2" + exeSuffix) 3489 tg.run("build", "-o", exe1, "cgotest") 3490 tg.run("build", "-x", "-o", exe2, "cgotest") 3491 b1, err := ioutil.ReadFile(exe1) 3492 tg.must(err) 3493 b2, err := ioutil.ReadFile(exe2) 3494 tg.must(err) 3495 3496 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) { 3497 t.Skip("skipping because C compiler does not support -fdebug-prefix-map") 3498 } 3499 if !bytes.Equal(b1, b2) { 3500 t.Error("building cgotest twice did not produce the same output") 3501 } 3502 } 3503 3504 // Issue 14444: go get -u .../ duplicate loads errors 3505 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) { 3506 testenv.MustHaveExternalNetwork(t) 3507 3508 tg := testgo(t) 3509 defer tg.cleanup() 3510 tg.makeTempdir() 3511 tg.setenv("GOPATH", tg.path(".")) 3512 tg.run("get", "-u", ".../") 3513 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache") 3514 } 3515 3516 // Issue 17119 more duplicate load errors 3517 func TestIssue17119(t *testing.T) { 3518 testenv.MustHaveExternalNetwork(t) 3519 3520 tg := testgo(t) 3521 defer tg.cleanup() 3522 tg.parallel() 3523 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3524 tg.runFail("build", "dupload") 3525 tg.grepBothNot("duplicate load|internal error", "internal error") 3526 } 3527 3528 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) { 3529 tg := testgo(t) 3530 defer tg.cleanup() 3531 // TODO: tg.parallel() 3532 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal") 3533 tg.grepBothNot("^ok", "test passed unexpectedly") 3534 tg.grepBoth("FAIL.*benchfatal", "test did not run everything") 3535 } 3536 3537 func TestBinaryOnlyPackages(t *testing.T) { 3538 tg := testgo(t) 3539 defer tg.cleanup() 3540 tg.parallel() 3541 tg.makeTempdir() 3542 tg.setenv("GOPATH", tg.path(".")) 3543 3544 tg.tempFile("src/p1/p1.go", `//go:binary-only-package 3545 3546 package p1 3547 `) 3548 tg.wantStale("p1", "cannot access install target", "p1 is binary-only but has no binary, should be stale") 3549 tg.runFail("install", "p1") 3550 tg.grepStderr("missing or invalid package binary", "did not report attempt to compile binary-only package") 3551 3552 tg.tempFile("src/p1/p1.go", ` 3553 package p1 3554 import "fmt" 3555 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } } 3556 `) 3557 tg.run("install", "p1") 3558 os.Remove(tg.path("src/p1/p1.go")) 3559 tg.mustNotExist(tg.path("src/p1/p1.go")) 3560 3561 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great 3562 3563 package p2 3564 import "p1" 3565 func F() { p1.F(true) } 3566 `) 3567 tg.runFail("install", "p2") 3568 tg.grepStderr("no Go files", "did not complain about missing sources") 3569 3570 tg.tempFile("src/p1/missing.go", `//go:binary-only-package 3571 3572 package p1 3573 func G() 3574 `) 3575 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (first)") 3576 tg.run("install", "-x", "p1") // no-op, up to date 3577 tg.grepBothNot("/compile", "should not have run compiler") 3578 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail) 3579 tg.wantNotStale("p2", "", "should NOT want to rebuild p2") 3580 3581 // changes to the non-source-code do not matter, 3582 // and only one file needs the special comment. 3583 tg.tempFile("src/p1/missing2.go", ` 3584 package p1 3585 func H() 3586 `) 3587 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (second)") 3588 tg.wantNotStale("p2", "", "should NOT want to rebuild p2") 3589 3590 tg.tempFile("src/p3/p3.go", ` 3591 package main 3592 import ( 3593 "p1" 3594 "p2" 3595 ) 3596 func main() { 3597 p1.F(false) 3598 p2.F() 3599 } 3600 `) 3601 tg.run("install", "p3") 3602 3603 tg.run("run", tg.path("src/p3/p3.go")) 3604 tg.grepStdout("hello from p1", "did not see message from p1") 3605 3606 tg.tempFile("src/p4/p4.go", `package main`) 3607 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package 3608 3609 // +build asdf 3610 3611 package main 3612 `) 3613 tg.run("list", "-f", "{{.BinaryOnly}}", "p4") 3614 tg.grepStdout("false", "did not see BinaryOnly=false for p4") 3615 } 3616 3617 // Issue 16050. 3618 func TestAlwaysLinkSysoFiles(t *testing.T) { 3619 tg := testgo(t) 3620 defer tg.cleanup() 3621 tg.parallel() 3622 tg.tempDir("src/syso") 3623 tg.tempFile("src/syso/a.syso", ``) 3624 tg.tempFile("src/syso/b.go", `package syso`) 3625 tg.setenv("GOPATH", tg.path(".")) 3626 3627 // We should see the .syso file regardless of the setting of 3628 // CGO_ENABLED. 3629 3630 tg.setenv("CGO_ENABLED", "1") 3631 tg.run("list", "-f", "{{.SysoFiles}}", "syso") 3632 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1") 3633 3634 tg.setenv("CGO_ENABLED", "0") 3635 tg.run("list", "-f", "{{.SysoFiles}}", "syso") 3636 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0") 3637 } 3638 3639 // Issue 16120. 3640 func TestGenerateUsesBuildContext(t *testing.T) { 3641 if runtime.GOOS == "windows" { 3642 t.Skip("this test won't run under Windows") 3643 } 3644 3645 tg := testgo(t) 3646 defer tg.cleanup() 3647 tg.parallel() 3648 tg.tempDir("src/gen") 3649 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n") 3650 tg.setenv("GOPATH", tg.path(".")) 3651 3652 tg.setenv("GOOS", "linux") 3653 tg.setenv("GOARCH", "amd64") 3654 tg.run("generate", "gen") 3655 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination") 3656 3657 tg.setenv("GOOS", "darwin") 3658 tg.setenv("GOARCH", "386") 3659 tg.run("generate", "gen") 3660 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination") 3661 } 3662 3663 // Issue 14450: go get -u .../ tried to import not downloaded package 3664 func TestGoGetUpdateWithWildcard(t *testing.T) { 3665 testenv.MustHaveExternalNetwork(t) 3666 3667 tg := testgo(t) 3668 defer tg.cleanup() 3669 tg.parallel() 3670 tg.makeTempdir() 3671 tg.setenv("GOPATH", tg.path(".")) 3672 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a" 3673 tg.run("get", aPkgImportPath) 3674 tg.run("get", "-u", ".../") 3675 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path") 3676 3677 var expectedPkgPaths = []string{ 3678 "src/github.com/tmwh/go-get-issue-14450/b", 3679 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c", 3680 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d", 3681 } 3682 3683 for _, importPath := range expectedPkgPaths { 3684 _, err := os.Stat(tg.path(importPath)) 3685 tg.must(err) 3686 } 3687 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e" 3688 tg.mustNotExist(tg.path(notExpectedPkgPath)) 3689 } 3690 3691 func TestGoEnv(t *testing.T) { 3692 tg := testgo(t) 3693 tg.parallel() 3694 defer tg.cleanup() 3695 tg.setenv("GOARCH", "arm") 3696 tg.run("env", "GOARCH") 3697 tg.grepStdout("^arm$", "GOARCH not honored") 3698 3699 tg.run("env", "GCCGO") 3700 tg.grepStdout(".", "GCCGO unexpectedly empty") 3701 3702 tg.run("env", "CGO_CFLAGS") 3703 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty") 3704 3705 tg.setenv("CGO_CFLAGS", "-foobar") 3706 tg.run("env", "CGO_CFLAGS") 3707 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored") 3708 3709 tg.setenv("CC", "gcc -fmust -fgo -ffaster") 3710 tg.run("env", "CC") 3711 tg.grepStdout("gcc", "CC not found") 3712 tg.run("env", "GOGCCFLAGS") 3713 tg.grepStdout("-ffaster", "CC arguments not found") 3714 } 3715 3716 const ( 3717 noMatchesPattern = `(?m)^ok.*\[no tests to run\]` 3718 okPattern = `(?m)^ok` 3719 ) 3720 3721 func TestMatchesNoTests(t *testing.T) { 3722 tg := testgo(t) 3723 defer tg.cleanup() 3724 // TODO: tg.parallel() 3725 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go") 3726 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3727 } 3728 3729 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) { 3730 tg := testgo(t) 3731 defer tg.cleanup() 3732 tg.parallel() 3733 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3734 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror") 3735 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3736 tg.grepBoth("FAIL", "go test did not say FAIL") 3737 } 3738 3739 func TestMatchesNoBenchmarksIsOK(t *testing.T) { 3740 tg := testgo(t) 3741 defer tg.cleanup() 3742 // TODO: tg.parallel() 3743 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go") 3744 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3745 tg.grepBoth(okPattern, "go test did not say ok") 3746 } 3747 3748 func TestMatchesOnlyExampleIsOK(t *testing.T) { 3749 tg := testgo(t) 3750 defer tg.cleanup() 3751 // TODO: tg.parallel() 3752 tg.run("test", "-run", "Example", "testdata/example1_test.go") 3753 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3754 tg.grepBoth(okPattern, "go test did not say ok") 3755 } 3756 3757 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) { 3758 tg := testgo(t) 3759 defer tg.cleanup() 3760 // TODO: tg.parallel() 3761 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go") 3762 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3763 tg.grepBoth(okPattern, "go test did not say ok") 3764 } 3765 3766 func TestBenchmarkLabels(t *testing.T) { 3767 tg := testgo(t) 3768 defer tg.cleanup() 3769 // TODO: tg.parallel() 3770 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3771 tg.run("test", "-run", "^$", "-bench", ".", "bench") 3772 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos") 3773 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch") 3774 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench") 3775 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times") 3776 } 3777 3778 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) { 3779 tg := testgo(t) 3780 defer tg.cleanup() 3781 // TODO: tg.parallel() 3782 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go") 3783 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos") 3784 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch") 3785 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:") 3786 } 3787 3788 func TestMatchesOnlyTestIsOK(t *testing.T) { 3789 tg := testgo(t) 3790 defer tg.cleanup() 3791 // TODO: tg.parallel() 3792 tg.run("test", "-run", "Test", "testdata/standalone_test.go") 3793 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3794 tg.grepBoth(okPattern, "go test did not say ok") 3795 } 3796 3797 func TestMatchesNoTestsWithSubtests(t *testing.T) { 3798 tg := testgo(t) 3799 defer tg.cleanup() 3800 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go") 3801 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3802 } 3803 3804 func TestMatchesNoSubtestsMatch(t *testing.T) { 3805 tg := testgo(t) 3806 defer tg.cleanup() 3807 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go") 3808 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3809 } 3810 3811 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) { 3812 tg := testgo(t) 3813 defer tg.cleanup() 3814 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go") 3815 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3816 tg.grepBoth("FAIL", "go test did not say FAIL") 3817 } 3818 3819 func TestMatchesOnlySubtestIsOK(t *testing.T) { 3820 tg := testgo(t) 3821 defer tg.cleanup() 3822 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go") 3823 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3824 tg.grepBoth(okPattern, "go test did not say ok") 3825 } 3826 3827 func TestMatchesNoSubtestsParallel(t *testing.T) { 3828 tg := testgo(t) 3829 defer tg.cleanup() 3830 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go") 3831 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3832 } 3833 3834 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) { 3835 tg := testgo(t) 3836 defer tg.cleanup() 3837 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go") 3838 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3839 tg.grepBoth(okPattern, "go test did not say ok") 3840 } 3841 3842 // Issue 18845 3843 func TestBenchTimeout(t *testing.T) { 3844 tg := testgo(t) 3845 defer tg.cleanup() 3846 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go") 3847 } 3848 3849 func TestLinkXImportPathEscape(t *testing.T) { 3850 // golang.org/issue/16710 3851 tg := testgo(t) 3852 defer tg.cleanup() 3853 tg.parallel() 3854 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3855 exe := "./linkx" + exeSuffix 3856 tg.creatingTemp(exe) 3857 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main") 3858 out, err := exec.Command(exe).CombinedOutput() 3859 if err != nil { 3860 tg.t.Fatal(err) 3861 } 3862 if string(out) != "linkXworked\n" { 3863 tg.t.Log(string(out)) 3864 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`) 3865 } 3866 } 3867 3868 // Issue 18044. 3869 func TestLdBindNow(t *testing.T) { 3870 tg := testgo(t) 3871 defer tg.cleanup() 3872 tg.parallel() 3873 tg.setenv("LD_BIND_NOW", "1") 3874 tg.run("help") 3875 } 3876 3877 // Issue 18225. 3878 // This is really a cmd/asm issue but this is a convenient place to test it. 3879 func TestConcurrentAsm(t *testing.T) { 3880 tg := testgo(t) 3881 defer tg.cleanup() 3882 tg.parallel() 3883 asm := `DATA ·constants<>+0x0(SB)/8,$0 3884 GLOBL ·constants<>(SB),8,$8 3885 ` 3886 tg.tempFile("go/src/p/a.s", asm) 3887 tg.tempFile("go/src/p/b.s", asm) 3888 tg.tempFile("go/src/p/p.go", `package p`) 3889 tg.setenv("GOPATH", tg.path("go")) 3890 tg.run("build", "p") 3891 } 3892 3893 // Issue 18778. 3894 func TestDotDotDotOutsideGOPATH(t *testing.T) { 3895 tg := testgo(t) 3896 defer tg.cleanup() 3897 3898 tg.tempFile("pkgs/a.go", `package x`) 3899 tg.tempFile("pkgs/a_test.go", `package x_test 3900 import "testing" 3901 func TestX(t *testing.T) {}`) 3902 3903 tg.tempFile("pkgs/a/a.go", `package a`) 3904 tg.tempFile("pkgs/a/a_test.go", `package a_test 3905 import "testing" 3906 func TestA(t *testing.T) {}`) 3907 3908 tg.cd(tg.path("pkgs")) 3909 tg.run("build", "./...") 3910 tg.run("test", "./...") 3911 tg.run("list", "./...") 3912 tg.grepStdout("pkgs$", "expected package not listed") 3913 tg.grepStdout("pkgs/a", "expected package not listed") 3914 } 3915 3916 // Issue 18975. 3917 func TestFFLAGS(t *testing.T) { 3918 if !canCgo { 3919 t.Skip("skipping because cgo not enabled") 3920 } 3921 3922 tg := testgo(t) 3923 defer tg.cleanup() 3924 tg.parallel() 3925 3926 tg.tempFile("p/src/p/main.go", `package main 3927 // #cgo FFLAGS: -no-such-fortran-flag 3928 import "C" 3929 func main() {} 3930 `) 3931 tg.tempFile("p/src/p/a.f", `! comment`) 3932 tg.setenv("GOPATH", tg.path("p")) 3933 3934 // This should normally fail because we are passing an unknown flag, 3935 // but issue #19080 points to Fortran compilers that succeed anyhow. 3936 // To work either way we call doRun directly rather than run or runFail. 3937 tg.doRun([]string{"build", "-x", "p"}) 3938 3939 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`) 3940 } 3941 3942 // Issue 19198. 3943 // This is really a cmd/link issue but this is a convenient place to test it. 3944 func TestDuplicateGlobalAsmSymbols(t *testing.T) { 3945 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" { 3946 t.Skipf("skipping test on %s", runtime.GOARCH) 3947 } 3948 if !canCgo { 3949 t.Skip("skipping because cgo not enabled") 3950 } 3951 3952 tg := testgo(t) 3953 defer tg.cleanup() 3954 tg.parallel() 3955 3956 asm := ` 3957 #include "textflag.h" 3958 3959 DATA sym<>+0x0(SB)/8,$0 3960 GLOBL sym<>(SB),(NOPTR+RODATA),$8 3961 3962 TEXT ·Data(SB),NOSPLIT,$0 3963 MOVB sym<>(SB), AX 3964 MOVB AX, ret+0(FP) 3965 RET 3966 ` 3967 tg.tempFile("go/src/a/a.s", asm) 3968 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`) 3969 tg.tempFile("go/src/b/b.s", asm) 3970 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`) 3971 tg.tempFile("go/src/p/p.go", ` 3972 package main 3973 import "a" 3974 import "b" 3975 import "C" 3976 func main() { 3977 _ = a.Data() + b.Data() 3978 } 3979 `) 3980 tg.setenv("GOPATH", tg.path("go")) 3981 exe := filepath.Join(tg.tempdir, "p.exe") 3982 tg.creatingTemp(exe) 3983 tg.run("build", "-o", exe, "p") 3984 } 3985 3986 func TestBuildTagsNoComma(t *testing.T) { 3987 tg := testgo(t) 3988 defer tg.cleanup() 3989 tg.makeTempdir() 3990 tg.setenv("GOPATH", tg.path("go")) 3991 tg.run("install", "-tags", "tag1 tag2", "math") 3992 tg.runFail("install", "-tags", "tag1,tag2", "math") 3993 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error") 3994 tg.runFail("build", "-tags", "tag1,tag2", "math") 3995 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error") 3996 } 3997 3998 func copyFile(src, dst string, perm os.FileMode) error { 3999 sf, err := os.Open(src) 4000 if err != nil { 4001 return err 4002 } 4003 defer sf.Close() 4004 4005 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) 4006 if err != nil { 4007 return err 4008 } 4009 4010 _, err = io.Copy(df, sf) 4011 err2 := df.Close() 4012 if err != nil { 4013 return err 4014 } 4015 return err2 4016 } 4017 4018 func TestExecutableGOROOT(t *testing.T) { 4019 if runtime.GOOS == "openbsd" { 4020 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS) 4021 } 4022 4023 // Env with no GOROOT. 4024 var env []string 4025 for _, e := range os.Environ() { 4026 if !strings.HasPrefix(e, "GOROOT=") { 4027 env = append(env, e) 4028 } 4029 } 4030 4031 check := func(t *testing.T, exe, want string) { 4032 cmd := exec.Command(exe, "env", "GOROOT") 4033 cmd.Env = env 4034 out, err := cmd.CombinedOutput() 4035 if err != nil { 4036 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out) 4037 } 4038 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out))) 4039 if err != nil { 4040 t.Fatal(err) 4041 } 4042 want, err = filepath.EvalSymlinks(want) 4043 if err != nil { 4044 t.Fatal(err) 4045 } 4046 if !strings.EqualFold(goroot, want) { 4047 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want) 4048 } else { 4049 t.Logf("go env GOROOT: %s", goroot) 4050 } 4051 } 4052 4053 // Note: Must not call tg methods inside subtests: tg is attached to outer t. 4054 tg := testgo(t) 4055 defer tg.cleanup() 4056 4057 tg.makeTempdir() 4058 tg.tempDir("new/bin") 4059 newGoTool := tg.path("new/bin/go" + exeSuffix) 4060 tg.must(copyFile(tg.goTool(), newGoTool, 0775)) 4061 newRoot := tg.path("new") 4062 4063 t.Run("RelocatedExe", func(t *testing.T) { 4064 t.Skip("TODO: skipping known broken test; see golang.org/issue/20284") 4065 4066 // Should fall back to default location in binary. 4067 // No way to dig out other than look at source code. 4068 data, err := ioutil.ReadFile("../../runtime/internal/sys/zversion.go") 4069 if err != nil { 4070 t.Fatal(err) 4071 } 4072 m := regexp.MustCompile("const DefaultGoroot = `([^`]+)`").FindStringSubmatch(string(data)) 4073 if m == nil { 4074 t.Fatal("cannot find DefaultGoroot in ../../runtime/internal/sys/zversion.go") 4075 } 4076 check(t, newGoTool, m[1]) 4077 }) 4078 4079 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT, 4080 // so it should find the new tree. 4081 tg.tempDir("new/pkg/tool") 4082 t.Run("RelocatedTree", func(t *testing.T) { 4083 check(t, newGoTool, newRoot) 4084 }) 4085 4086 tg.tempDir("other/bin") 4087 symGoTool := tg.path("other/bin/go" + exeSuffix) 4088 4089 // Symlink into go tree should still find go tree. 4090 t.Run("SymlinkedExe", func(t *testing.T) { 4091 testenv.MustHaveSymlink(t) 4092 if err := os.Symlink(newGoTool, symGoTool); err != nil { 4093 t.Fatal(err) 4094 } 4095 check(t, symGoTool, newRoot) 4096 }) 4097 } 4098 4099 func TestNeedVersion(t *testing.T) { 4100 tg := testgo(t) 4101 defer tg.cleanup() 4102 tg.parallel() 4103 tg.tempFile("goversion.go", `package main; func main() {}`) 4104 path := tg.path("goversion.go") 4105 tg.setenv("TESTGO_VERSION", "go1.testgo") 4106 tg.runFail("run", path) 4107 tg.grepStderr("compile", "does not match go tool version") 4108 } 4109 4110 // Test that user can override default code generation flags. 4111 func TestUserOverrideFlags(t *testing.T) { 4112 if !canCgo { 4113 t.Skip("skipping because cgo not enabled") 4114 } 4115 if runtime.GOOS != "linux" { 4116 // We are testing platform-independent code, so it's 4117 // OK to skip cases that work differently. 4118 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS) 4119 } 4120 4121 tg := testgo(t) 4122 defer tg.cleanup() 4123 tg.parallel() 4124 tg.tempFile("override.go", `package main 4125 4126 import "C" 4127 4128 //export GoFunc 4129 func GoFunc() {} 4130 4131 func main() {}`) 4132 tg.creatingTemp("override.a") 4133 tg.creatingTemp("override.h") 4134 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=-shared=false", tg.path("override.go")) 4135 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag") 4136 } 4137 4138 func TestCgoFlagContainsSpace(t *testing.T) { 4139 if !canCgo { 4140 t.Skip("skipping because cgo not enabled") 4141 } 4142 4143 tg := testgo(t) 4144 defer tg.cleanup() 4145 4146 ccName := filepath.Base(testCC) 4147 4148 tg.tempFile(fmt.Sprintf("src/%s/main.go", ccName), fmt.Sprintf(`package main 4149 import ( 4150 "os" 4151 "os/exec" 4152 "strings" 4153 ) 4154 4155 func main() { 4156 cmd := exec.Command(%q, os.Args[1:]...) 4157 cmd.Stdin = os.Stdin 4158 cmd.Stdout = os.Stdout 4159 cmd.Stderr = os.Stderr 4160 err := cmd.Run() 4161 if err != nil { 4162 panic(err) 4163 } 4164 4165 if os.Args[len(os.Args)-1] == "trivial.c" { 4166 return 4167 } 4168 4169 var success bool 4170 for _, arg := range os.Args { 4171 switch { 4172 case strings.Contains(arg, "c flags"): 4173 if success { 4174 panic("duplicate CFLAGS") 4175 } 4176 success = true 4177 case strings.Contains(arg, "ld flags"): 4178 if success { 4179 panic("duplicate LDFLAGS") 4180 } 4181 success = true 4182 } 4183 } 4184 if !success { 4185 panic("args should contains '-Ic flags' or '-Lld flags'") 4186 } 4187 } 4188 `, testCC)) 4189 tg.cd(tg.path(fmt.Sprintf("src/%s", ccName))) 4190 tg.run("build") 4191 tg.setenv("CC", tg.path(fmt.Sprintf("src/%s/%s", ccName, ccName))) 4192 4193 tg.tempFile("src/cgo/main.go", `package main 4194 // #cgo CFLAGS: -I"c flags" 4195 // #cgo LDFLAGS: -L"ld flags" 4196 import "C" 4197 func main() {} 4198 `) 4199 tg.cd(tg.path("src/cgo")) 4200 tg.run("run", "main.go") 4201 } 4202 4203 // Issue #20435. 4204 func TestGoTestRaceCoverModeFailures(t *testing.T) { 4205 if !canRace { 4206 t.Skip("skipping because race detector not supported") 4207 } 4208 4209 tg := testgo(t) 4210 tg.parallel() 4211 defer tg.cleanup() 4212 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 4213 4214 tg.run("test", "testrace") 4215 4216 tg.runFail("test", "-race", "-covermode=set", "testrace") 4217 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed") 4218 tg.grepBothNot("PASS", "something passed") 4219 } 4220 4221 // Issue 9737: verify that GOARM and GO386 affect the computed build ID. 4222 func TestBuildIDContainsArchModeEnv(t *testing.T) { 4223 if testing.Short() { 4224 t.Skip("skipping in short mode") 4225 } 4226 4227 var tg *testgoData 4228 testWith := func(before, after func()) func(*testing.T) { 4229 return func(t *testing.T) { 4230 tg = testgo(t) 4231 defer tg.cleanup() 4232 tg.tempFile("src/mycmd/x.go", `package main 4233 func main() {}`) 4234 tg.setenv("GOPATH", tg.path(".")) 4235 4236 tg.cd(tg.path("src/mycmd")) 4237 tg.setenv("GOOS", "linux") 4238 before() 4239 tg.run("install", "mycmd") 4240 after() 4241 tg.wantStale("mycmd", "build ID mismatch", "should be stale after environment variable change") 4242 } 4243 } 4244 4245 t.Run("386", testWith(func() { 4246 tg.setenv("GOARCH", "386") 4247 tg.setenv("GO386", "387") 4248 }, func() { 4249 tg.setenv("GO386", "sse2") 4250 })) 4251 4252 t.Run("arm", testWith(func() { 4253 tg.setenv("GOARCH", "arm") 4254 tg.setenv("GOARM", "5") 4255 }, func() { 4256 tg.setenv("GOARM", "7") 4257 })) 4258 } 4259 4260 func TestTestRegexps(t *testing.T) { 4261 tg := testgo(t) 4262 defer tg.cleanup() 4263 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 4264 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp") 4265 var lines []string 4266 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") { 4267 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") { 4268 lines = append(lines, line) 4269 } 4270 } 4271 4272 // Important parts: 4273 // TestX is run, twice 4274 // TestX/Y is run, twice 4275 // TestXX is run, twice 4276 // TestZ is not run 4277 // BenchmarkX is run but only with N=1, once 4278 // BenchmarkXX is run but only with N=1, once 4279 // BenchmarkX/Y is run in full, twice 4280 want := `=== RUN TestX 4281 === RUN TestX/Y 4282 x_test.go:6: LOG: X running 4283 x_test.go:8: LOG: Y running 4284 === RUN TestXX 4285 z_test.go:10: LOG: XX running 4286 === RUN TestX 4287 === RUN TestX/Y 4288 x_test.go:6: LOG: X running 4289 x_test.go:8: LOG: Y running 4290 === RUN TestXX 4291 z_test.go:10: LOG: XX running 4292 --- BENCH: BenchmarkX/Y 4293 x_test.go:15: LOG: Y running N=1 4294 x_test.go:15: LOG: Y running N=100 4295 x_test.go:15: LOG: Y running N=10000 4296 x_test.go:15: LOG: Y running N=1000000 4297 x_test.go:15: LOG: Y running N=100000000 4298 x_test.go:15: LOG: Y running N=2000000000 4299 --- BENCH: BenchmarkX/Y 4300 x_test.go:15: LOG: Y running N=1 4301 x_test.go:15: LOG: Y running N=100 4302 x_test.go:15: LOG: Y running N=10000 4303 x_test.go:15: LOG: Y running N=1000000 4304 x_test.go:15: LOG: Y running N=100000000 4305 x_test.go:15: LOG: Y running N=2000000000 4306 --- BENCH: BenchmarkX 4307 x_test.go:13: LOG: X running N=1 4308 --- BENCH: BenchmarkXX 4309 z_test.go:18: LOG: XX running N=1 4310 ` 4311 4312 have := strings.Join(lines, "") 4313 if have != want { 4314 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want) 4315 } 4316 } 4317 4318 func TestListTests(t *testing.T) { 4319 var tg *testgoData 4320 testWith := func(listName, expected string) func(*testing.T) { 4321 return func(t *testing.T) { 4322 tg = testgo(t) 4323 defer tg.cleanup() 4324 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName)) 4325 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected)) 4326 } 4327 } 4328 4329 t.Run("Test", testWith("Test", "TestSimple")) 4330 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple")) 4331 t.Run("Example1", testWith("Example", "ExampleSimple")) 4332 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput")) 4333 }