1// Copyright 2011 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 5package build 6 7import ( 8 "flag" 9 "internal/testenv" 10 "io" 11 "os" 12 "path/filepath" 13 "reflect" 14 "runtime" 15 "strings" 16 "testing" 17) 18 19func TestMain(m *testing.M) { 20 flag.Parse() 21 if goTool, err := testenv.GoTool(); err == nil { 22 os.Setenv("PATH", filepath.Dir(goTool)+string(os.PathListSeparator)+os.Getenv("PATH")) 23 } 24 os.Exit(m.Run()) 25} 26 27func TestMatch(t *testing.T) { 28 ctxt := Default 29 what := "default" 30 match := func(tag string, want map[string]bool) { 31 t.Helper() 32 m := make(map[string]bool) 33 if !ctxt.match(tag, m) { 34 t.Errorf("%s context should match %s, does not", what, tag) 35 } 36 if !reflect.DeepEqual(m, want) { 37 t.Errorf("%s tags = %v, want %v", tag, m, want) 38 } 39 } 40 nomatch := func(tag string, want map[string]bool) { 41 t.Helper() 42 m := make(map[string]bool) 43 if ctxt.match(tag, m) { 44 t.Errorf("%s context should NOT match %s, does", what, tag) 45 } 46 if !reflect.DeepEqual(m, want) { 47 t.Errorf("%s tags = %v, want %v", tag, m, want) 48 } 49 } 50 51 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true}) 52 match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 53 nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 54 55 what = "modified" 56 ctxt.BuildTags = []string{"foo"} 57 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true}) 58 match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 59 nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 60 match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true}) 61 nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true}) 62} 63 64func TestDotSlashImport(t *testing.T) { 65 p, err := ImportDir("testdata/other", 0) 66 if err != nil { 67 t.Fatal(err) 68 } 69 if len(p.Imports) != 1 || p.Imports[0] != "./file" { 70 t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports) 71 } 72 73 p1, err := Import("./file", "testdata/other", 0) 74 if err != nil { 75 t.Fatal(err) 76 } 77 if p1.Name != "file" { 78 t.Fatalf("./file: Name=%q, want %q", p1.Name, "file") 79 } 80 dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows 81 if p1.Dir != dir { 82 t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir) 83 } 84} 85 86func TestEmptyImport(t *testing.T) { 87 p, err := Import("", Default.GOROOT, FindOnly) 88 if err == nil { 89 t.Fatal(`Import("") returned nil error.`) 90 } 91 if p == nil { 92 t.Fatal(`Import("") returned nil package.`) 93 } 94 if p.ImportPath != "" { 95 t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "") 96 } 97} 98 99func TestEmptyFolderImport(t *testing.T) { 100 _, err := Import(".", "testdata/empty", 0) 101 if _, ok := err.(*NoGoError); !ok { 102 t.Fatal(`Import("testdata/empty") did not return NoGoError.`) 103 } 104} 105 106func TestMultiplePackageImport(t *testing.T) { 107 _, err := Import(".", "testdata/multi", 0) 108 mpe, ok := err.(*MultiplePackageError) 109 if !ok { 110 t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`) 111 } 112 want := &MultiplePackageError{ 113 Dir: filepath.FromSlash("testdata/multi"), 114 Packages: []string{"main", "test_package"}, 115 Files: []string{"file.go", "file_appengine.go"}, 116 } 117 if !reflect.DeepEqual(mpe, want) { 118 t.Errorf("got %#v; want %#v", mpe, want) 119 } 120} 121 122func TestLocalDirectory(t *testing.T) { 123 t.Skip("does not work with gccgo") 124 if runtime.GOOS == "ios" { 125 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) 126 } 127 128 cwd, err := os.Getwd() 129 if err != nil { 130 t.Fatal(err) 131 } 132 133 p, err := ImportDir(cwd, 0) 134 if err != nil { 135 t.Fatal(err) 136 } 137 if p.ImportPath != "go/build" { 138 t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build") 139 } 140} 141 142var shouldBuildTests = []struct { 143 name string 144 content string 145 tags map[string]bool 146 binaryOnly bool 147 shouldBuild bool 148 err error 149}{ 150 { 151 name: "Yes", 152 content: "// +build yes\n\n" + 153 "package main\n", 154 tags: map[string]bool{"yes": true}, 155 shouldBuild: true, 156 }, 157 { 158 name: "Or", 159 content: "// +build no yes\n\n" + 160 "package main\n", 161 tags: map[string]bool{"yes": true, "no": true}, 162 shouldBuild: true, 163 }, 164 { 165 name: "And", 166 content: "// +build no,yes\n\n" + 167 "package main\n", 168 tags: map[string]bool{"yes": true, "no": true}, 169 shouldBuild: false, 170 }, 171 { 172 name: "Cgo", 173 content: "// +build cgo\n\n" + 174 "// Copyright The Go Authors.\n\n" + 175 "// This package implements parsing of tags like\n" + 176 "// +build tag1\n" + 177 "package build", 178 tags: map[string]bool{"cgo": true}, 179 shouldBuild: false, 180 }, 181 { 182 name: "AfterPackage", 183 content: "// Copyright The Go Authors.\n\n" + 184 "package build\n\n" + 185 "// shouldBuild checks tags given by lines of the form\n" + 186 "// +build tag\n" + 187 "func shouldBuild(content []byte)\n", 188 tags: map[string]bool{}, 189 shouldBuild: true, 190 }, 191 { 192 name: "TooClose", 193 content: "// +build yes\n" + 194 "package main\n", 195 tags: map[string]bool{}, 196 shouldBuild: true, 197 }, 198 { 199 name: "TooCloseNo", 200 content: "// +build no\n" + 201 "package main\n", 202 tags: map[string]bool{}, 203 shouldBuild: true, 204 }, 205 { 206 name: "BinaryOnly", 207 content: "//go:binary-only-package\n" + 208 "// +build yes\n" + 209 "package main\n", 210 tags: map[string]bool{}, 211 binaryOnly: true, 212 shouldBuild: true, 213 }, 214 { 215 name: "ValidGoBuild", 216 content: "// +build yes\n\n" + 217 "//go:build no\n" + 218 "package main\n", 219 tags: map[string]bool{"yes": true}, 220 shouldBuild: true, 221 }, 222 { 223 name: "MissingBuild", 224 content: "//go:build no\n" + 225 "package main\n", 226 tags: map[string]bool{}, 227 shouldBuild: false, 228 err: errGoBuildWithoutBuild, 229 }, 230 { 231 name: "MissingBuild2", 232 content: "/* */\n" + 233 "// +build yes\n\n" + 234 "//go:build no\n" + 235 "package main\n", 236 tags: map[string]bool{}, 237 shouldBuild: false, 238 err: errGoBuildWithoutBuild, 239 }, 240 { 241 name: "MissingBuild2", 242 content: "/*\n" + 243 "// +build yes\n\n" + 244 "*/\n" + 245 "//go:build no\n" + 246 "package main\n", 247 tags: map[string]bool{}, 248 shouldBuild: false, 249 err: errGoBuildWithoutBuild, 250 }, 251 { 252 name: "Comment1", 253 content: "/*\n" + 254 "//go:build no\n" + 255 "*/\n\n" + 256 "package main\n", 257 tags: map[string]bool{}, 258 shouldBuild: true, 259 }, 260 { 261 name: "Comment2", 262 content: "/*\n" + 263 "text\n" + 264 "*/\n\n" + 265 "//go:build no\n" + 266 "package main\n", 267 tags: map[string]bool{}, 268 shouldBuild: false, 269 err: errGoBuildWithoutBuild, 270 }, 271 { 272 name: "Comment3", 273 content: "/*/*/ /* hi *//* \n" + 274 "text\n" + 275 "*/\n\n" + 276 "//go:build no\n" + 277 "package main\n", 278 tags: map[string]bool{}, 279 shouldBuild: false, 280 err: errGoBuildWithoutBuild, 281 }, 282 { 283 name: "Comment4", 284 content: "/**///go:build no\n" + 285 "package main\n", 286 tags: map[string]bool{}, 287 shouldBuild: true, 288 }, 289 { 290 name: "Comment5", 291 content: "/**/\n" + 292 "//go:build no\n" + 293 "package main\n", 294 tags: map[string]bool{}, 295 shouldBuild: false, 296 err: errGoBuildWithoutBuild, 297 }, 298} 299 300func TestShouldBuild(t *testing.T) { 301 for _, tt := range shouldBuildTests { 302 t.Run(tt.name, func(t *testing.T) { 303 ctx := &Context{BuildTags: []string{"yes"}} 304 tags := map[string]bool{} 305 shouldBuild, binaryOnly, err := ctx.shouldBuild([]byte(tt.content), tags) 306 if shouldBuild != tt.shouldBuild || binaryOnly != tt.binaryOnly || !reflect.DeepEqual(tags, tt.tags) || err != tt.err { 307 t.Errorf("mismatch:\n"+ 308 "have shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v\n"+ 309 "want shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v", 310 shouldBuild, binaryOnly, tags, err, 311 tt.shouldBuild, tt.binaryOnly, tt.tags, tt.err) 312 } 313 }) 314 } 315} 316 317func TestGoodOSArchFile(t *testing.T) { 318 ctx := &Context{BuildTags: []string{"linux"}, GOOS: "darwin"} 319 m := map[string]bool{} 320 want := map[string]bool{"linux": true} 321 if !ctx.goodOSArchFile("hello_linux.go", m) { 322 t.Errorf("goodOSArchFile(hello_linux.go) = false, want true") 323 } 324 if !reflect.DeepEqual(m, want) { 325 t.Errorf("goodOSArchFile(hello_linux.go) tags = %v, want %v", m, want) 326 } 327} 328 329type readNopCloser struct { 330 io.Reader 331} 332 333func (r readNopCloser) Close() error { 334 return nil 335} 336 337var ( 338 ctxtP9 = Context{GOARCH: "arm", GOOS: "plan9"} 339 ctxtAndroid = Context{GOARCH: "arm", GOOS: "android"} 340) 341 342var matchFileTests = []struct { 343 ctxt Context 344 name string 345 data string 346 match bool 347}{ 348 {ctxtP9, "foo_arm.go", "", true}, 349 {ctxtP9, "foo1_arm.go", "// +build linux\n\npackage main\n", false}, 350 {ctxtP9, "foo_darwin.go", "", false}, 351 {ctxtP9, "foo.go", "", true}, 352 {ctxtP9, "foo1.go", "// +build linux\n\npackage main\n", false}, 353 {ctxtP9, "foo.badsuffix", "", false}, 354 {ctxtAndroid, "foo_linux.go", "", true}, 355 {ctxtAndroid, "foo_android.go", "", true}, 356 {ctxtAndroid, "foo_plan9.go", "", false}, 357 {ctxtAndroid, "android.go", "", true}, 358 {ctxtAndroid, "plan9.go", "", true}, 359 {ctxtAndroid, "plan9_test.go", "", true}, 360 {ctxtAndroid, "arm.s", "", true}, 361 {ctxtAndroid, "amd64.s", "", true}, 362} 363 364func TestMatchFile(t *testing.T) { 365 for _, tt := range matchFileTests { 366 ctxt := tt.ctxt 367 ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) { 368 if path != "x+"+tt.name { 369 t.Fatalf("OpenFile asked for %q, expected %q", path, "x+"+tt.name) 370 } 371 return &readNopCloser{strings.NewReader(tt.data)}, nil 372 } 373 ctxt.JoinPath = func(elem ...string) string { 374 return strings.Join(elem, "+") 375 } 376 match, err := ctxt.MatchFile("x", tt.name) 377 if match != tt.match || err != nil { 378 t.Fatalf("MatchFile(%q) = %v, %v, want %v, nil", tt.name, match, err, tt.match) 379 } 380 } 381} 382 383func TestImportCmd(t *testing.T) { 384 t.Skip("does not work with gccgo") 385 if runtime.GOOS == "ios" { 386 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) 387 } 388 389 p, err := Import("cmd/internal/objfile", "", 0) 390 if err != nil { 391 t.Fatal(err) 392 } 393 if !strings.HasSuffix(filepath.ToSlash(p.Dir), "src/cmd/internal/objfile") { 394 t.Fatalf("Import cmd/internal/objfile returned Dir=%q, want %q", filepath.ToSlash(p.Dir), ".../src/cmd/internal/objfile") 395 } 396} 397 398var ( 399 expandSrcDirPath = filepath.Join(string(filepath.Separator)+"projects", "src", "add") 400) 401 402var expandSrcDirTests = []struct { 403 input, expected string 404}{ 405 {"-L ${SRCDIR}/libs -ladd", "-L /projects/src/add/libs -ladd"}, 406 {"${SRCDIR}/add_linux_386.a -pthread -lstdc++", "/projects/src/add/add_linux_386.a -pthread -lstdc++"}, 407 {"Nothing to expand here!", "Nothing to expand here!"}, 408 {"$", "$"}, 409 {"$$", "$$"}, 410 {"${", "${"}, 411 {"$}", "$}"}, 412 {"$FOO ${BAR}", "$FOO ${BAR}"}, 413 {"Find me the $SRCDIRECTORY.", "Find me the $SRCDIRECTORY."}, 414 {"$SRCDIR is missing braces", "$SRCDIR is missing braces"}, 415} 416 417func TestExpandSrcDir(t *testing.T) { 418 for _, test := range expandSrcDirTests { 419 output, _ := expandSrcDir(test.input, expandSrcDirPath) 420 if output != test.expected { 421 t.Errorf("%q expands to %q with SRCDIR=%q when %q is expected", test.input, output, expandSrcDirPath, test.expected) 422 } else { 423 t.Logf("%q expands to %q with SRCDIR=%q", test.input, output, expandSrcDirPath) 424 } 425 } 426} 427 428func TestShellSafety(t *testing.T) { 429 tests := []struct { 430 input, srcdir, expected string 431 result bool 432 }{ 433 {"-I${SRCDIR}/../include", "/projects/src/issue 11868", "-I/projects/src/issue 11868/../include", true}, 434 {"-I${SRCDIR}", "~wtf$@%^", "-I~wtf$@%^", true}, 435 {"-X${SRCDIR}/1,${SRCDIR}/2", "/projects/src/issue 11868", "-X/projects/src/issue 11868/1,/projects/src/issue 11868/2", true}, 436 {"-I/tmp -I/tmp", "/tmp2", "-I/tmp -I/tmp", true}, 437 {"-I/tmp", "/tmp/[0]", "-I/tmp", true}, 438 {"-I${SRCDIR}/dir", "/tmp/[0]", "-I/tmp/[0]/dir", false}, 439 {"-I${SRCDIR}/dir", "/tmp/go go", "-I/tmp/go go/dir", true}, 440 {"-I${SRCDIR}/dir dir", "/tmp/go", "-I/tmp/go/dir dir", true}, 441 } 442 for _, test := range tests { 443 output, ok := expandSrcDir(test.input, test.srcdir) 444 if ok != test.result { 445 t.Errorf("Expected %t while %q expands to %q with SRCDIR=%q; got %t", test.result, test.input, output, test.srcdir, ok) 446 } 447 if output != test.expected { 448 t.Errorf("Expected %q while %q expands with SRCDIR=%q; got %q", test.expected, test.input, test.srcdir, output) 449 } 450 } 451} 452 453// Want to get a "cannot find package" error when directory for package does not exist. 454// There should be valid partial information in the returned non-nil *Package. 455func TestImportDirNotExist(t *testing.T) { 456 testenv.MustHaveGoBuild(t) // really must just have source 457 ctxt := Default 458 459 emptyDir, err := os.MkdirTemp("", t.Name()) 460 if err != nil { 461 t.Fatal(err) 462 } 463 defer os.RemoveAll(emptyDir) 464 465 ctxt.GOPATH = emptyDir 466 ctxt.Dir = emptyDir 467 468 tests := []struct { 469 label string 470 path, srcDir string 471 mode ImportMode 472 }{ 473 {"Import(full, 0)", "go/build/doesnotexist", "", 0}, 474 {"Import(local, 0)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), 0}, 475 {"Import(full, FindOnly)", "go/build/doesnotexist", "", FindOnly}, 476 {"Import(local, FindOnly)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), FindOnly}, 477 } 478 479 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 480 481 for _, GO111MODULE := range []string{"off", "on"} { 482 t.Run("GO111MODULE="+GO111MODULE, func(t *testing.T) { 483 os.Setenv("GO111MODULE", GO111MODULE) 484 485 for _, test := range tests { 486 p, err := ctxt.Import(test.path, test.srcDir, test.mode) 487 488 errOk := (err != nil && strings.HasPrefix(err.Error(), "cannot find package")) 489 wantErr := `"cannot find package" error` 490 if test.srcDir == "" { 491 if err != nil && strings.Contains(err.Error(), "is not in GOROOT") { 492 errOk = true 493 } 494 wantErr = `"cannot find package" or "is not in GOROOT" error` 495 } 496 if !errOk { 497 t.Errorf("%s got error: %q, want %s", test.label, err, wantErr) 498 } 499 // If an error occurs, build.Import is documented to return 500 // a non-nil *Package containing partial information. 501 if p == nil { 502 t.Fatalf(`%s got nil p, want non-nil *Package`, test.label) 503 } 504 // Verify partial information in p. 505 if p.ImportPath != "go/build/doesnotexist" { 506 t.Errorf(`%s got p.ImportPath: %q, want "go/build/doesnotexist"`, test.label, p.ImportPath) 507 } 508 } 509 }) 510 } 511} 512 513func TestImportVendor(t *testing.T) { 514 testenv.MustHaveGoBuild(t) // really must just have source 515 516 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 517 os.Setenv("GO111MODULE", "off") 518 519 ctxt := Default 520 wd, err := os.Getwd() 521 if err != nil { 522 t.Fatal(err) 523 } 524 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 525 p, err := ctxt.Import("c/d", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 526 if err != nil { 527 t.Fatalf("cannot find vendored c/d from testdata src/a/b directory: %v", err) 528 } 529 want := "a/vendor/c/d" 530 if p.ImportPath != want { 531 t.Fatalf("Import succeeded but found %q, want %q", p.ImportPath, want) 532 } 533} 534 535func TestImportVendorFailure(t *testing.T) { 536 testenv.MustHaveGoBuild(t) // really must just have source 537 538 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 539 os.Setenv("GO111MODULE", "off") 540 541 ctxt := Default 542 wd, err := os.Getwd() 543 if err != nil { 544 t.Fatal(err) 545 } 546 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 547 p, err := ctxt.Import("x.com/y/z", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 548 if err == nil { 549 t.Fatalf("found made-up package x.com/y/z in %s", p.Dir) 550 } 551 552 e := err.Error() 553 if !strings.Contains(e, " (vendor tree)") { 554 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e) 555 } 556} 557 558func TestImportVendorParentFailure(t *testing.T) { 559 testenv.MustHaveGoBuild(t) // really must just have source 560 561 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 562 os.Setenv("GO111MODULE", "off") 563 564 ctxt := Default 565 wd, err := os.Getwd() 566 if err != nil { 567 t.Fatal(err) 568 } 569 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 570 // This import should fail because the vendor/c directory has no source code. 571 p, err := ctxt.Import("c", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 572 if err == nil { 573 t.Fatalf("found empty parent in %s", p.Dir) 574 } 575 if p != nil && p.Dir != "" { 576 t.Fatalf("decided to use %s", p.Dir) 577 } 578 e := err.Error() 579 if !strings.Contains(e, " (vendor tree)") { 580 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e) 581 } 582} 583 584// Check that a package is loaded in module mode if GO111MODULE=on, even when 585// no go.mod file is present. It should fail to resolve packages outside std. 586// Verifies golang.org/issue/34669. 587func TestImportPackageOutsideModule(t *testing.T) { 588 testenv.MustHaveGoBuild(t) 589 590 // Disable module fetching for this test so that 'go list' fails quickly 591 // without trying to find the latest version of a module. 592 defer os.Setenv("GOPROXY", os.Getenv("GOPROXY")) 593 os.Setenv("GOPROXY", "off") 594 595 // Create a GOPATH in a temporary directory. We don't use testdata 596 // because it's in GOROOT, which interferes with the module heuristic. 597 gopath, err := os.MkdirTemp("", "gobuild-notmodule") 598 if err != nil { 599 t.Fatal(err) 600 } 601 defer os.RemoveAll(gopath) 602 if err := os.MkdirAll(filepath.Join(gopath, "src/example.com/p"), 0777); err != nil { 603 t.Fatal(err) 604 } 605 if err := os.WriteFile(filepath.Join(gopath, "src/example.com/p/p.go"), []byte("package p"), 0666); err != nil { 606 t.Fatal(err) 607 } 608 609 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 610 os.Setenv("GO111MODULE", "on") 611 defer os.Setenv("GOPATH", os.Getenv("GOPATH")) 612 os.Setenv("GOPATH", gopath) 613 ctxt := Default 614 ctxt.GOPATH = gopath 615 ctxt.Dir = filepath.Join(gopath, "src/example.com/p") 616 617 want := "go.mod file not found in current directory or any parent directory" 618 if _, err := ctxt.Import("example.com/p", gopath, FindOnly); err == nil { 619 t.Fatal("importing package when no go.mod is present succeeded unexpectedly") 620 } else if errStr := err.Error(); !strings.Contains(errStr, want) { 621 t.Fatalf("error when importing package when no go.mod is present: got %q; want %q", errStr, want) 622 } else { 623 t.Logf(`ctxt.Import("example.com/p", _, FindOnly): %v`, err) 624 } 625} 626 627func TestImportDirTarget(t *testing.T) { 628 testenv.MustHaveGoBuild(t) // really must just have source 629 ctxt := Default 630 ctxt.GOPATH = "" 631 p, err := ctxt.ImportDir(filepath.Join(ctxt.GOROOT, "src/path"), 0) 632 if err != nil { 633 t.Fatal(err) 634 } 635 if p.PkgTargetRoot == "" || p.PkgObj == "" { 636 t.Errorf("p.PkgTargetRoot == %q, p.PkgObj == %q, want non-empty", p.PkgTargetRoot, p.PkgObj) 637 } 638} 639 640// TestIssue23594 prevents go/build from regressing and populating Package.Doc 641// from comments in test files. 642func TestIssue23594(t *testing.T) { 643 // Package testdata/doc contains regular and external test files 644 // with comments attached to their package declarations. The names of the files 645 // ensure that we see the comments from the test files first. 646 p, err := ImportDir("testdata/doc", 0) 647 if err != nil { 648 t.Fatalf("could not import testdata: %v", err) 649 } 650 651 if p.Doc != "Correct" { 652 t.Fatalf("incorrectly set .Doc to %q", p.Doc) 653 } 654} 655 656// TestMissingImportErrorRepetition checks that when an unknown package is 657// imported, the package path is only shown once in the error. 658// Verifies golang.org/issue/34752. 659func TestMissingImportErrorRepetition(t *testing.T) { 660 testenv.MustHaveGoBuild(t) // need 'go list' internally 661 tmp, err := os.MkdirTemp("", "") 662 if err != nil { 663 t.Fatal(err) 664 } 665 defer os.RemoveAll(tmp) 666 if err := os.WriteFile(filepath.Join(tmp, "go.mod"), []byte("module m"), 0666); err != nil { 667 t.Fatal(err) 668 } 669 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE")) 670 os.Setenv("GO111MODULE", "on") 671 defer os.Setenv("GOPROXY", os.Getenv("GOPROXY")) 672 os.Setenv("GOPROXY", "off") 673 defer os.Setenv("GONOPROXY", os.Getenv("GONOPROXY")) 674 os.Setenv("GONOPROXY", "none") 675 676 ctxt := Default 677 ctxt.Dir = tmp 678 679 pkgPath := "example.com/hello" 680 _, err = ctxt.Import(pkgPath, tmp, FindOnly) 681 if err == nil { 682 t.Fatal("unexpected success") 683 } 684 685 // Don't count the package path with a URL like https://...?go-get=1. 686 // See golang.org/issue/35986. 687 errStr := strings.ReplaceAll(err.Error(), "://"+pkgPath+"?go-get=1", "://...?go-get=1") 688 689 // Also don't count instances in suggested "go get" or similar commands 690 // (see https://golang.org/issue/41576). The suggested command typically 691 // follows a semicolon. 692 errStr = strings.SplitN(errStr, ";", 2)[0] 693 694 if n := strings.Count(errStr, pkgPath); n != 1 { 695 t.Fatalf("package path %q appears in error %d times; should appear once\nerror: %v", pkgPath, n, err) 696 } 697} 698 699// TestCgoImportsIgnored checks that imports in cgo files are not included 700// in the imports list when cgo is disabled. 701// Verifies golang.org/issue/35946. 702func TestCgoImportsIgnored(t *testing.T) { 703 ctxt := Default 704 ctxt.CgoEnabled = false 705 p, err := ctxt.ImportDir("testdata/cgo_disabled", 0) 706 if err != nil { 707 t.Fatal(err) 708 } 709 for _, path := range p.Imports { 710 if path == "should/be/ignored" { 711 t.Errorf("found import %q in ignored cgo file", path) 712 } 713 } 714} 715