github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/go/build/build_test.go (about) 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 5 package build 6 7 import ( 8 "internal/testenv" 9 "io" 10 "os" 11 "path/filepath" 12 "reflect" 13 "runtime" 14 "strings" 15 "testing" 16 ) 17 18 func TestMatch(t *testing.T) { 19 ctxt := Default 20 what := "default" 21 match := func(tag string, want map[string]bool) { 22 m := make(map[string]bool) 23 if !ctxt.match(tag, m) { 24 t.Errorf("%s context should match %s, does not", what, tag) 25 } 26 if !reflect.DeepEqual(m, want) { 27 t.Errorf("%s tags = %v, want %v", tag, m, want) 28 } 29 } 30 nomatch := func(tag string, want map[string]bool) { 31 m := make(map[string]bool) 32 if ctxt.match(tag, m) { 33 t.Errorf("%s context should NOT match %s, does", what, tag) 34 } 35 if !reflect.DeepEqual(m, want) { 36 t.Errorf("%s tags = %v, want %v", tag, m, want) 37 } 38 } 39 40 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true}) 41 match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 42 nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 43 44 what = "modified" 45 ctxt.BuildTags = []string{"foo"} 46 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true}) 47 match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 48 nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true}) 49 match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true}) 50 nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true}) 51 nomatch("!", map[string]bool{}) 52 } 53 54 func TestDotSlashImport(t *testing.T) { 55 p, err := ImportDir("testdata/other", 0) 56 if err != nil { 57 t.Fatal(err) 58 } 59 if len(p.Imports) != 1 || p.Imports[0] != "./file" { 60 t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports) 61 } 62 63 p1, err := Import("./file", "testdata/other", 0) 64 if err != nil { 65 t.Fatal(err) 66 } 67 if p1.Name != "file" { 68 t.Fatalf("./file: Name=%q, want %q", p1.Name, "file") 69 } 70 dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows 71 if p1.Dir != dir { 72 t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir) 73 } 74 } 75 76 func TestEmptyImport(t *testing.T) { 77 p, err := Import("", Default.GOROOT, FindOnly) 78 if err == nil { 79 t.Fatal(`Import("") returned nil error.`) 80 } 81 if p == nil { 82 t.Fatal(`Import("") returned nil package.`) 83 } 84 if p.ImportPath != "" { 85 t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "") 86 } 87 } 88 89 func TestEmptyFolderImport(t *testing.T) { 90 _, err := Import(".", "testdata/empty", 0) 91 if _, ok := err.(*NoGoError); !ok { 92 t.Fatal(`Import("testdata/empty") did not return NoGoError.`) 93 } 94 } 95 96 func TestMultiplePackageImport(t *testing.T) { 97 _, err := Import(".", "testdata/multi", 0) 98 mpe, ok := err.(*MultiplePackageError) 99 if !ok { 100 t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`) 101 } 102 want := &MultiplePackageError{ 103 Dir: filepath.FromSlash("testdata/multi"), 104 Packages: []string{"main", "test_package"}, 105 Files: []string{"file.go", "file_appengine.go"}, 106 } 107 if !reflect.DeepEqual(mpe, want) { 108 t.Errorf("got %#v; want %#v", mpe, want) 109 } 110 } 111 112 func TestLocalDirectory(t *testing.T) { 113 if runtime.GOOS == "darwin" { 114 switch runtime.GOARCH { 115 case "arm", "arm64": 116 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) 117 } 118 } 119 120 cwd, err := os.Getwd() 121 if err != nil { 122 t.Fatal(err) 123 } 124 125 p, err := ImportDir(cwd, 0) 126 if err != nil { 127 t.Fatal(err) 128 } 129 if p.ImportPath != "go/build" { 130 t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build") 131 } 132 } 133 134 func TestShouldBuild(t *testing.T) { 135 const file1 = "// +build tag1\n\n" + 136 "package main\n" 137 want1 := map[string]bool{"tag1": true} 138 139 const file2 = "// +build cgo\n\n" + 140 "// This package implements parsing of tags like\n" + 141 "// +build tag1\n" + 142 "package build" 143 want2 := map[string]bool{"cgo": true} 144 145 const file3 = "// Copyright The Go Authors.\n\n" + 146 "package build\n\n" + 147 "// shouldBuild checks tags given by lines of the form\n" + 148 "// +build tag\n" + 149 "func shouldBuild(content []byte)\n" 150 want3 := map[string]bool{} 151 152 ctx := &Context{BuildTags: []string{"tag1"}} 153 m := map[string]bool{} 154 if !ctx.shouldBuild([]byte(file1), m, nil) { 155 t.Errorf("shouldBuild(file1) = false, want true") 156 } 157 if !reflect.DeepEqual(m, want1) { 158 t.Errorf("shouldBuild(file1) tags = %v, want %v", m, want1) 159 } 160 161 m = map[string]bool{} 162 if ctx.shouldBuild([]byte(file2), m, nil) { 163 t.Errorf("shouldBuild(file2) = true, want false") 164 } 165 if !reflect.DeepEqual(m, want2) { 166 t.Errorf("shouldBuild(file2) tags = %v, want %v", m, want2) 167 } 168 169 m = map[string]bool{} 170 ctx = &Context{BuildTags: nil} 171 if !ctx.shouldBuild([]byte(file3), m, nil) { 172 t.Errorf("shouldBuild(file3) = false, want true") 173 } 174 if !reflect.DeepEqual(m, want3) { 175 t.Errorf("shouldBuild(file3) tags = %v, want %v", m, want3) 176 } 177 } 178 179 func TestGoodOSArchFile(t *testing.T) { 180 ctx := &Context{BuildTags: []string{"linux"}, GOOS: "darwin"} 181 m := map[string]bool{} 182 want := map[string]bool{"linux": true} 183 if !ctx.goodOSArchFile("hello_linux.go", m) { 184 t.Errorf("goodOSArchFile(hello_linux.go) = false, want true") 185 } 186 if !reflect.DeepEqual(m, want) { 187 t.Errorf("goodOSArchFile(hello_linux.go) tags = %v, want %v", m, want) 188 } 189 } 190 191 type readNopCloser struct { 192 io.Reader 193 } 194 195 func (r readNopCloser) Close() error { 196 return nil 197 } 198 199 var ( 200 ctxtP9 = Context{GOARCH: "arm", GOOS: "plan9"} 201 ctxtAndroid = Context{GOARCH: "arm", GOOS: "android"} 202 ) 203 204 var matchFileTests = []struct { 205 ctxt Context 206 name string 207 data string 208 match bool 209 }{ 210 {ctxtP9, "foo_arm.go", "", true}, 211 {ctxtP9, "foo1_arm.go", "// +build linux\n\npackage main\n", false}, 212 {ctxtP9, "foo_darwin.go", "", false}, 213 {ctxtP9, "foo.go", "", true}, 214 {ctxtP9, "foo1.go", "// +build linux\n\npackage main\n", false}, 215 {ctxtP9, "foo.badsuffix", "", false}, 216 {ctxtAndroid, "foo_linux.go", "", true}, 217 {ctxtAndroid, "foo_android.go", "", true}, 218 {ctxtAndroid, "foo_plan9.go", "", false}, 219 {ctxtAndroid, "android.go", "", true}, 220 {ctxtAndroid, "plan9.go", "", true}, 221 {ctxtAndroid, "plan9_test.go", "", true}, 222 {ctxtAndroid, "arm.s", "", true}, 223 {ctxtAndroid, "amd64.s", "", true}, 224 } 225 226 func TestMatchFile(t *testing.T) { 227 for _, tt := range matchFileTests { 228 ctxt := tt.ctxt 229 ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) { 230 if path != "x+"+tt.name { 231 t.Fatalf("OpenFile asked for %q, expected %q", path, "x+"+tt.name) 232 } 233 return &readNopCloser{strings.NewReader(tt.data)}, nil 234 } 235 ctxt.JoinPath = func(elem ...string) string { 236 return strings.Join(elem, "+") 237 } 238 match, err := ctxt.MatchFile("x", tt.name) 239 if match != tt.match || err != nil { 240 t.Fatalf("MatchFile(%q) = %v, %v, want %v, nil", tt.name, match, err, tt.match) 241 } 242 } 243 } 244 245 func TestImportCmd(t *testing.T) { 246 if runtime.GOOS == "darwin" { 247 switch runtime.GOARCH { 248 case "arm", "arm64": 249 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH) 250 } 251 } 252 253 p, err := Import("cmd/internal/objfile", "", 0) 254 if err != nil { 255 t.Fatal(err) 256 } 257 if !strings.HasSuffix(filepath.ToSlash(p.Dir), "src/cmd/internal/objfile") { 258 t.Fatalf("Import cmd/internal/objfile returned Dir=%q, want %q", filepath.ToSlash(p.Dir), ".../src/cmd/internal/objfile") 259 } 260 } 261 262 var ( 263 expandSrcDirPath = filepath.Join(string(filepath.Separator)+"projects", "src", "add") 264 ) 265 266 var expandSrcDirTests = []struct { 267 input, expected string 268 }{ 269 {"-L ${SRCDIR}/libs -ladd", "-L /projects/src/add/libs -ladd"}, 270 {"${SRCDIR}/add_linux_386.a -pthread -lstdc++", "/projects/src/add/add_linux_386.a -pthread -lstdc++"}, 271 {"Nothing to expand here!", "Nothing to expand here!"}, 272 {"$", "$"}, 273 {"$$", "$$"}, 274 {"${", "${"}, 275 {"$}", "$}"}, 276 {"$FOO ${BAR}", "$FOO ${BAR}"}, 277 {"Find me the $SRCDIRECTORY.", "Find me the $SRCDIRECTORY."}, 278 {"$SRCDIR is missing braces", "$SRCDIR is missing braces"}, 279 } 280 281 func TestExpandSrcDir(t *testing.T) { 282 for _, test := range expandSrcDirTests { 283 output, _ := expandSrcDir(test.input, expandSrcDirPath) 284 if output != test.expected { 285 t.Errorf("%q expands to %q with SRCDIR=%q when %q is expected", test.input, output, expandSrcDirPath, test.expected) 286 } else { 287 t.Logf("%q expands to %q with SRCDIR=%q", test.input, output, expandSrcDirPath) 288 } 289 } 290 } 291 292 func TestShellSafety(t *testing.T) { 293 tests := []struct { 294 input, srcdir, expected string 295 result bool 296 }{ 297 {"-I${SRCDIR}/../include", "/projects/src/issue 11868", "-I/projects/src/issue 11868/../include", true}, 298 {"-I${SRCDIR}", "wtf$@%", "-Iwtf$@%", true}, 299 {"-X${SRCDIR}/1,${SRCDIR}/2", "/projects/src/issue 11868", "-X/projects/src/issue 11868/1,/projects/src/issue 11868/2", true}, 300 {"-I/tmp -I/tmp", "/tmp2", "-I/tmp -I/tmp", true}, 301 {"-I/tmp", "/tmp/[0]", "-I/tmp", true}, 302 {"-I${SRCDIR}/dir", "/tmp/[0]", "-I/tmp/[0]/dir", false}, 303 {"-I${SRCDIR}/dir", "/tmp/go go", "-I/tmp/go go/dir", true}, 304 {"-I${SRCDIR}/dir dir", "/tmp/go", "-I/tmp/go/dir dir", true}, 305 } 306 for _, test := range tests { 307 output, ok := expandSrcDir(test.input, test.srcdir) 308 if ok != test.result { 309 t.Errorf("Expected %t while %q expands to %q with SRCDIR=%q; got %t", test.result, test.input, output, test.srcdir, ok) 310 } 311 if output != test.expected { 312 t.Errorf("Expected %q while %q expands with SRCDIR=%q; got %q", test.expected, test.input, test.srcdir, output) 313 } 314 } 315 } 316 317 // Want to get a "cannot find package" error when directory for package does not exist. 318 // There should be valid partial information in the returned non-nil *Package. 319 func TestImportDirNotExist(t *testing.T) { 320 testenv.MustHaveGoBuild(t) // really must just have source 321 ctxt := Default 322 ctxt.GOPATH = "" 323 324 tests := []struct { 325 label string 326 path, srcDir string 327 mode ImportMode 328 }{ 329 {"Import(full, 0)", "go/build/doesnotexist", "", 0}, 330 {"Import(local, 0)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), 0}, 331 {"Import(full, FindOnly)", "go/build/doesnotexist", "", FindOnly}, 332 {"Import(local, FindOnly)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), FindOnly}, 333 } 334 for _, test := range tests { 335 p, err := ctxt.Import(test.path, test.srcDir, test.mode) 336 if err == nil || !strings.HasPrefix(err.Error(), "cannot find package") { 337 t.Errorf(`%s got error: %q, want "cannot find package" error`, test.label, err) 338 } 339 // If an error occurs, build.Import is documented to return 340 // a non-nil *Package containing partial information. 341 if p == nil { 342 t.Fatalf(`%s got nil p, want non-nil *Package`, test.label) 343 } 344 // Verify partial information in p. 345 if p.ImportPath != "go/build/doesnotexist" { 346 t.Errorf(`%s got p.ImportPath: %q, want "go/build/doesnotexist"`, test.label, p.ImportPath) 347 } 348 } 349 } 350 351 func TestImportVendor(t *testing.T) { 352 testenv.MustHaveGoBuild(t) // really must just have source 353 ctxt := Default 354 wd, err := os.Getwd() 355 if err != nil { 356 t.Fatal(err) 357 } 358 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 359 p, err := ctxt.Import("c/d", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 360 if err != nil { 361 t.Fatalf("cannot find vendored c/d from testdata src/a/b directory: %v", err) 362 } 363 want := "a/vendor/c/d" 364 if p.ImportPath != want { 365 t.Fatalf("Import succeeded but found %q, want %q", p.ImportPath, want) 366 } 367 } 368 369 func TestImportVendorFailure(t *testing.T) { 370 testenv.MustHaveGoBuild(t) // really must just have source 371 ctxt := Default 372 wd, err := os.Getwd() 373 if err != nil { 374 t.Fatal(err) 375 } 376 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 377 p, err := ctxt.Import("x.com/y/z", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 378 if err == nil { 379 t.Fatalf("found made-up package x.com/y/z in %s", p.Dir) 380 } 381 382 e := err.Error() 383 if !strings.Contains(e, " (vendor tree)") { 384 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e) 385 } 386 } 387 388 func TestImportVendorParentFailure(t *testing.T) { 389 testenv.MustHaveGoBuild(t) // really must just have source 390 ctxt := Default 391 wd, err := os.Getwd() 392 if err != nil { 393 t.Fatal(err) 394 } 395 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor") 396 // This import should fail because the vendor/c directory has no source code. 397 p, err := ctxt.Import("c", filepath.Join(ctxt.GOPATH, "src/a/b"), 0) 398 if err == nil { 399 t.Fatalf("found empty parent in %s", p.Dir) 400 } 401 if p != nil && p.Dir != "" { 402 t.Fatalf("decided to use %s", p.Dir) 403 } 404 e := err.Error() 405 if !strings.Contains(e, " (vendor tree)") { 406 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e) 407 } 408 } 409 410 func TestImportDirTarget(t *testing.T) { 411 testenv.MustHaveGoBuild(t) // really must just have source 412 ctxt := Default 413 ctxt.GOPATH = "" 414 p, err := ctxt.ImportDir(filepath.Join(ctxt.GOROOT, "src/path"), 0) 415 if err != nil { 416 t.Fatal(err) 417 } 418 if p.PkgTargetRoot == "" || p.PkgObj == "" { 419 t.Errorf("p.PkgTargetRoot == %q, p.PkgObj == %q, want non-empty", p.PkgTargetRoot, p.PkgObj) 420 } 421 } 422 423 // TestIssue23594 prevents go/build from regressing and populating Package.Doc 424 // from comments in test files. 425 func TestIssue23594(t *testing.T) { 426 // Package testdata/doc contains regular and external test files 427 // with comments attached to their package declarations. The names of the files 428 // ensure that we see the comments from the test files first. 429 p, err := ImportDir("testdata/doc", 0) 430 if err != nil { 431 t.Fatalf("could not import testdata: %v", err) 432 } 433 434 if p.Doc != "Correct" { 435 t.Fatalf("incorrectly set .Doc to %q", p.Doc) 436 } 437 }