github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/go/internal/gcimporter/gcimporter_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 gcimporter 6 7 import ( 8 "bytes" 9 "fmt" 10 "internal/testenv" 11 "io/ioutil" 12 "os" 13 "os/exec" 14 "path/filepath" 15 "runtime" 16 "strings" 17 "testing" 18 "time" 19 20 "go/types" 21 ) 22 23 // skipSpecialPlatforms causes the test to be skipped for platforms where 24 // builders (build.golang.org) don't have access to compiled packages for 25 // import. 26 func skipSpecialPlatforms(t *testing.T) { 27 switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform { 28 case "nacl-amd64p32", 29 "nacl-386", 30 "nacl-arm", 31 "darwin-arm", 32 "darwin-arm64": 33 t.Skipf("no compiled packages available for import on %s", platform) 34 } 35 } 36 37 func compile(t *testing.T, dirname, filename string) string { 38 cmd := exec.Command(testenv.GoToolPath(t), "tool", "compile", filename) 39 cmd.Dir = dirname 40 out, err := cmd.CombinedOutput() 41 if err != nil { 42 t.Logf("%s", out) 43 t.Fatalf("go tool compile %s failed: %s", filename, err) 44 } 45 // filename should end with ".go" 46 return filepath.Join(dirname, filename[:len(filename)-2]+"o") 47 } 48 49 func testPath(t *testing.T, path, srcDir string) *types.Package { 50 t0 := time.Now() 51 pkg, err := Import(make(map[string]*types.Package), path, srcDir, nil) 52 if err != nil { 53 t.Errorf("testPath(%s): %s", path, err) 54 return nil 55 } 56 t.Logf("testPath(%s): %v", path, time.Since(t0)) 57 return pkg 58 } 59 60 const maxTime = 30 * time.Second 61 62 func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) { 63 dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir) 64 list, err := ioutil.ReadDir(dirname) 65 if err != nil { 66 t.Fatalf("testDir(%s): %s", dirname, err) 67 } 68 for _, f := range list { 69 if time.Now().After(endTime) { 70 t.Log("testing time used up") 71 return 72 } 73 switch { 74 case !f.IsDir(): 75 // try extensions 76 for _, ext := range pkgExts { 77 if strings.HasSuffix(f.Name(), ext) { 78 name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension 79 if testPath(t, filepath.Join(dir, name), dir) != nil { 80 nimports++ 81 } 82 } 83 } 84 case f.IsDir(): 85 nimports += testDir(t, filepath.Join(dir, f.Name()), endTime) 86 } 87 } 88 return 89 } 90 91 func TestImportTestdata(t *testing.T) { 92 // This package only handles gc export data. 93 if runtime.Compiler != "gc" { 94 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 95 } 96 97 if outFn := compile(t, "testdata", "exports.go"); outFn != "" { 98 defer os.Remove(outFn) 99 } 100 101 if pkg := testPath(t, "./testdata/exports", "."); pkg != nil { 102 // The package's Imports list must include all packages 103 // explicitly imported by exports.go, plus all packages 104 // referenced indirectly via exported objects in exports.go. 105 // With the textual export format, the list may also include 106 // additional packages that are not strictly required for 107 // import processing alone (they are exported to err "on 108 // the safe side"). 109 // TODO(gri) update the want list to be precise, now that 110 // the textual export data is gone. 111 got := fmt.Sprint(pkg.Imports()) 112 for _, want := range []string{"go/ast", "go/token"} { 113 if !strings.Contains(got, want) { 114 t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want) 115 } 116 } 117 } 118 } 119 120 func TestVersionHandling(t *testing.T) { 121 skipSpecialPlatforms(t) // we really only need to exclude nacl platforms, but this is fine 122 123 // This package only handles gc export data. 124 if runtime.Compiler != "gc" { 125 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 126 } 127 128 const dir = "./testdata/versions" 129 list, err := ioutil.ReadDir(dir) 130 if err != nil { 131 t.Fatal(err) 132 } 133 134 for _, f := range list { 135 name := f.Name() 136 if !strings.HasSuffix(name, ".a") { 137 continue // not a package file 138 } 139 if strings.Contains(name, "corrupted") { 140 continue // don't process a leftover corrupted file 141 } 142 pkgpath := "./" + name[:len(name)-2] 143 144 // test that export data can be imported 145 _, err := Import(make(map[string]*types.Package), pkgpath, dir, nil) 146 if err != nil { 147 t.Errorf("import %q failed: %v", pkgpath, err) 148 continue 149 } 150 151 // create file with corrupted export data 152 // 1) read file 153 data, err := ioutil.ReadFile(filepath.Join(dir, name)) 154 if err != nil { 155 t.Fatal(err) 156 } 157 // 2) find export data 158 i := bytes.Index(data, []byte("\n$$B\n")) + 5 159 j := bytes.Index(data[i:], []byte("\n$$\n")) + i 160 if i < 0 || j < 0 || i > j { 161 t.Fatalf("export data section not found (i = %d, j = %d)", i, j) 162 } 163 // 3) corrupt the data (increment every 7th byte) 164 for k := j - 13; k >= i; k -= 7 { 165 data[k]++ 166 } 167 // 4) write the file 168 pkgpath += "_corrupted" 169 filename := filepath.Join(dir, pkgpath) + ".a" 170 ioutil.WriteFile(filename, data, 0666) 171 defer os.Remove(filename) 172 173 // test that importing the corrupted file results in an error 174 _, err = Import(make(map[string]*types.Package), pkgpath, dir, nil) 175 if err == nil { 176 t.Errorf("import corrupted %q succeeded", pkgpath) 177 } else if msg := err.Error(); !strings.Contains(msg, "version skew") { 178 t.Errorf("import %q error incorrect (%s)", pkgpath, msg) 179 } 180 } 181 } 182 183 func TestImportStdLib(t *testing.T) { 184 skipSpecialPlatforms(t) 185 186 // This package only handles gc export data. 187 if runtime.Compiler != "gc" { 188 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 189 } 190 191 dt := maxTime 192 if testing.Short() && testenv.Builder() == "" { 193 dt = 10 * time.Millisecond 194 } 195 nimports := testDir(t, "", time.Now().Add(dt)) // installed packages 196 t.Logf("tested %d imports", nimports) 197 } 198 199 var importedObjectTests = []struct { 200 name string 201 want string 202 }{ 203 // non-interfaces 204 {"crypto.Hash", "type Hash uint"}, 205 {"go/ast.ObjKind", "type ObjKind int"}, 206 {"go/types.Qualifier", "type Qualifier func(*Package) string"}, 207 {"go/types.Comparable", "func Comparable(T Type) bool"}, 208 {"math.Pi", "const Pi untyped float"}, 209 {"math.Sin", "func Sin(x float64) float64"}, 210 211 // interfaces 212 {"context.Context", "type Context interface{Deadline() (deadline time.Time, ok bool); Done() <-chan struct{}; Err() error; Value(key interface{}) interface{}}"}, 213 {"crypto.Decrypter", "type Decrypter interface{Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error); Public() PublicKey}"}, 214 {"encoding.BinaryMarshaler", "type BinaryMarshaler interface{MarshalBinary() (data []byte, err error)}"}, 215 {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, 216 {"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"}, 217 {"go/ast.Node", "type Node interface{End() go/token.Pos; Pos() go/token.Pos}"}, 218 {"go/types.Type", "type Type interface{String() string; Underlying() Type}"}, 219 } 220 221 func TestImportedTypes(t *testing.T) { 222 skipSpecialPlatforms(t) 223 224 // This package only handles gc export data. 225 if runtime.Compiler != "gc" { 226 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 227 } 228 229 for _, test := range importedObjectTests { 230 s := strings.Split(test.name, ".") 231 if len(s) != 2 { 232 t.Fatal("inconsistent test data") 233 } 234 importPath := s[0] 235 objName := s[1] 236 237 pkg, err := Import(make(map[string]*types.Package), importPath, ".", nil) 238 if err != nil { 239 t.Error(err) 240 continue 241 } 242 243 obj := pkg.Scope().Lookup(objName) 244 if obj == nil { 245 t.Errorf("%s: object not found", test.name) 246 continue 247 } 248 249 got := types.ObjectString(obj, types.RelativeTo(pkg)) 250 if got != test.want { 251 t.Errorf("%s: got %q; want %q", test.name, got, test.want) 252 } 253 254 if named, _ := obj.Type().(*types.Named); named != nil { 255 verifyInterfaceMethodRecvs(t, named, 0) 256 } 257 } 258 } 259 260 // verifyInterfaceMethodRecvs verifies that method receiver types 261 // are named if the methods belong to a named interface type. 262 func verifyInterfaceMethodRecvs(t *testing.T, named *types.Named, level int) { 263 // avoid endless recursion in case of an embedding bug that lead to a cycle 264 if level > 10 { 265 t.Errorf("%s: embeds itself", named) 266 return 267 } 268 269 iface, _ := named.Underlying().(*types.Interface) 270 if iface == nil { 271 return // not an interface 272 } 273 274 // check explicitly declared methods 275 for i := 0; i < iface.NumExplicitMethods(); i++ { 276 m := iface.ExplicitMethod(i) 277 recv := m.Type().(*types.Signature).Recv() 278 if recv == nil { 279 t.Errorf("%s: missing receiver type", m) 280 continue 281 } 282 if recv.Type() != named { 283 t.Errorf("%s: got recv type %s; want %s", m, recv.Type(), named) 284 } 285 } 286 287 // check embedded interfaces (they are named, too) 288 for i := 0; i < iface.NumEmbeddeds(); i++ { 289 // embedding of interfaces cannot have cycles; recursion will terminate 290 verifyInterfaceMethodRecvs(t, iface.Embedded(i), level+1) 291 } 292 } 293 294 func TestIssue5815(t *testing.T) { 295 skipSpecialPlatforms(t) 296 297 // This package only handles gc export data. 298 if runtime.Compiler != "gc" { 299 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 300 } 301 302 pkg := importPkg(t, "strings") 303 304 scope := pkg.Scope() 305 for _, name := range scope.Names() { 306 obj := scope.Lookup(name) 307 if obj.Pkg() == nil { 308 t.Errorf("no pkg for %s", obj) 309 } 310 if tname, _ := obj.(*types.TypeName); tname != nil { 311 named := tname.Type().(*types.Named) 312 for i := 0; i < named.NumMethods(); i++ { 313 m := named.Method(i) 314 if m.Pkg() == nil { 315 t.Errorf("no pkg for %s", m) 316 } 317 } 318 } 319 } 320 } 321 322 // Smoke test to ensure that imported methods get the correct package. 323 func TestCorrectMethodPackage(t *testing.T) { 324 skipSpecialPlatforms(t) 325 326 // This package only handles gc export data. 327 if runtime.Compiler != "gc" { 328 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 329 } 330 331 imports := make(map[string]*types.Package) 332 _, err := Import(imports, "net/http", ".", nil) 333 if err != nil { 334 t.Fatal(err) 335 } 336 337 mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type() 338 mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex 339 sel := mset.Lookup(nil, "Lock") 340 lock := sel.Obj().(*types.Func) 341 if got, want := lock.Pkg().Path(), "sync"; got != want { 342 t.Errorf("got package path %q; want %q", got, want) 343 } 344 } 345 346 func TestIssue13566(t *testing.T) { 347 skipSpecialPlatforms(t) 348 349 // This package only handles gc export data. 350 if runtime.Compiler != "gc" { 351 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 352 } 353 354 // On windows, we have to set the -D option for the compiler to avoid having a drive 355 // letter and an illegal ':' in the import path - just skip it (see also issue #3483). 356 if runtime.GOOS == "windows" { 357 t.Skip("avoid dealing with relative paths/drive letters on windows") 358 } 359 360 if f := compile(t, "testdata", "a.go"); f != "" { 361 defer os.Remove(f) 362 } 363 if f := compile(t, "testdata", "b.go"); f != "" { 364 defer os.Remove(f) 365 } 366 367 // import must succeed (test for issue at hand) 368 pkg := importPkg(t, "./testdata/b") 369 370 // make sure all indirectly imported packages have names 371 for _, imp := range pkg.Imports() { 372 if imp.Name() == "" { 373 t.Errorf("no name for %s package", imp.Path()) 374 } 375 } 376 } 377 378 func TestIssue13898(t *testing.T) { 379 skipSpecialPlatforms(t) 380 381 // This package only handles gc export data. 382 if runtime.Compiler != "gc" { 383 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 384 } 385 386 // import go/internal/gcimporter which imports go/types partially 387 imports := make(map[string]*types.Package) 388 _, err := Import(imports, "go/internal/gcimporter", ".", nil) 389 if err != nil { 390 t.Fatal(err) 391 } 392 393 // look for go/types package 394 var goTypesPkg *types.Package 395 for path, pkg := range imports { 396 if path == "go/types" { 397 goTypesPkg = pkg 398 break 399 } 400 } 401 if goTypesPkg == nil { 402 t.Fatal("go/types not found") 403 } 404 405 // look for go/types.Object type 406 obj := lookupObj(t, goTypesPkg.Scope(), "Object") 407 typ, ok := obj.Type().(*types.Named) 408 if !ok { 409 t.Fatalf("go/types.Object type is %v; wanted named type", typ) 410 } 411 412 // lookup go/types.Object.Pkg method 413 m, index, indirect := types.LookupFieldOrMethod(typ, false, nil, "Pkg") 414 if m == nil { 415 t.Fatalf("go/types.Object.Pkg not found (index = %v, indirect = %v)", index, indirect) 416 } 417 418 // the method must belong to go/types 419 if m.Pkg().Path() != "go/types" { 420 t.Fatalf("found %v; want go/types", m.Pkg()) 421 } 422 } 423 424 func TestIssue15517(t *testing.T) { 425 skipSpecialPlatforms(t) 426 427 // This package only handles gc export data. 428 if runtime.Compiler != "gc" { 429 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 430 } 431 432 // On windows, we have to set the -D option for the compiler to avoid having a drive 433 // letter and an illegal ':' in the import path - just skip it (see also issue #3483). 434 if runtime.GOOS == "windows" { 435 t.Skip("avoid dealing with relative paths/drive letters on windows") 436 } 437 438 if f := compile(t, "testdata", "p.go"); f != "" { 439 defer os.Remove(f) 440 } 441 442 // Multiple imports of p must succeed without redeclaration errors. 443 // We use an import path that's not cleaned up so that the eventual 444 // file path for the package is different from the package path; this 445 // will expose the error if it is present. 446 // 447 // (Issue: Both the textual and the binary importer used the file path 448 // of the package to be imported as key into the shared packages map. 449 // However, the binary importer then used the package path to identify 450 // the imported package to mark it as complete; effectively marking the 451 // wrong package as complete. By using an "unclean" package path, the 452 // file and package path are different, exposing the problem if present. 453 // The same issue occurs with vendoring.) 454 imports := make(map[string]*types.Package) 455 for i := 0; i < 3; i++ { 456 if _, err := Import(imports, "./././testdata/p", ".", nil); err != nil { 457 t.Fatal(err) 458 } 459 } 460 } 461 462 func TestIssue15920(t *testing.T) { 463 skipSpecialPlatforms(t) 464 465 // This package only handles gc export data. 466 if runtime.Compiler != "gc" { 467 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 468 } 469 470 // On windows, we have to set the -D option for the compiler to avoid having a drive 471 // letter and an illegal ':' in the import path - just skip it (see also issue #3483). 472 if runtime.GOOS == "windows" { 473 t.Skip("avoid dealing with relative paths/drive letters on windows") 474 } 475 476 if f := compile(t, "testdata", "issue15920.go"); f != "" { 477 defer os.Remove(f) 478 } 479 480 importPkg(t, "./testdata/issue15920") 481 } 482 483 func TestIssue20046(t *testing.T) { 484 skipSpecialPlatforms(t) 485 486 // This package only handles gc export data. 487 if runtime.Compiler != "gc" { 488 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 489 } 490 491 // On windows, we have to set the -D option for the compiler to avoid having a drive 492 // letter and an illegal ':' in the import path - just skip it (see also issue #3483). 493 if runtime.GOOS == "windows" { 494 t.Skip("avoid dealing with relative paths/drive letters on windows") 495 } 496 497 if f := compile(t, "testdata", "issue20046.go"); f != "" { 498 defer os.Remove(f) 499 } 500 501 // "./issue20046".V.M must exist 502 pkg := importPkg(t, "./testdata/issue20046") 503 obj := lookupObj(t, pkg.Scope(), "V") 504 if m, index, indirect := types.LookupFieldOrMethod(obj.Type(), false, nil, "M"); m == nil { 505 t.Fatalf("V.M not found (index = %v, indirect = %v)", index, indirect) 506 } 507 } 508 509 func importPkg(t *testing.T, path string) *types.Package { 510 pkg, err := Import(make(map[string]*types.Package), path, ".", nil) 511 if err != nil { 512 t.Fatal(err) 513 } 514 return pkg 515 } 516 517 func lookupObj(t *testing.T, scope *types.Scope, name string) types.Object { 518 if obj := scope.Lookup(name); obj != nil { 519 return obj 520 } 521 t.Fatalf("%s not found", name) 522 return nil 523 }