github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/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 "fmt" 9 "internal/testenv" 10 "io/ioutil" 11 "os" 12 "os/exec" 13 "path/filepath" 14 "runtime" 15 "strings" 16 "testing" 17 "time" 18 19 "go/types" 20 ) 21 22 // skipSpecialPlatforms causes the test to be skipped for platforms where 23 // builders (build.golang.org) don't have access to compiled packages for 24 // import. 25 func skipSpecialPlatforms(t *testing.T) { 26 switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform { 27 case "nacl-amd64p32", 28 "nacl-386", 29 "nacl-arm", 30 "darwin-arm", 31 "darwin-arm64": 32 t.Skipf("no compiled packages available for import on %s", platform) 33 } 34 } 35 36 func compile(t *testing.T, dirname, filename string) string { 37 testenv.MustHaveGoBuild(t) 38 cmd := exec.Command("go", "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 // TODO(gri) Remove this function once we switched to new export format by default. 50 func compileNewExport(t *testing.T, dirname, filename string) string { 51 testenv.MustHaveGoBuild(t) 52 cmd := exec.Command("go", "tool", "compile", "-newexport", filename) 53 cmd.Dir = dirname 54 out, err := cmd.CombinedOutput() 55 if err != nil { 56 t.Logf("%s", out) 57 t.Fatalf("go tool compile %s failed: %s", filename, err) 58 } 59 // filename should end with ".go" 60 return filepath.Join(dirname, filename[:len(filename)-2]+"o") 61 } 62 63 func testPath(t *testing.T, path string) *types.Package { 64 t0 := time.Now() 65 pkg, err := Import(make(map[string]*types.Package), path) 66 if err != nil { 67 t.Errorf("testPath(%s): %s", path, err) 68 return nil 69 } 70 t.Logf("testPath(%s): %v", path, time.Since(t0)) 71 return pkg 72 } 73 74 const maxTime = 30 * time.Second 75 76 func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) { 77 dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir) 78 list, err := ioutil.ReadDir(dirname) 79 if err != nil { 80 t.Fatalf("testDir(%s): %s", dirname, err) 81 } 82 for _, f := range list { 83 if time.Now().After(endTime) { 84 t.Log("testing time used up") 85 return 86 } 87 switch { 88 case !f.IsDir(): 89 // try extensions 90 for _, ext := range pkgExts { 91 if strings.HasSuffix(f.Name(), ext) { 92 name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension 93 if testPath(t, filepath.Join(dir, name)) != nil { 94 nimports++ 95 } 96 } 97 } 98 case f.IsDir(): 99 nimports += testDir(t, filepath.Join(dir, f.Name()), endTime) 100 } 101 } 102 return 103 } 104 105 func TestImportTestdata(t *testing.T) { 106 // This package only handles gc export data. 107 if runtime.Compiler != "gc" { 108 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 109 return 110 } 111 112 if outFn := compile(t, "testdata", "exports.go"); outFn != "" { 113 defer os.Remove(outFn) 114 } 115 116 if pkg := testPath(t, "./testdata/exports"); pkg != nil { 117 // The package's Imports list must include all packages 118 // explicitly imported by exports.go, plus all packages 119 // referenced indirectly via exported objects in exports.go. 120 // With the textual export format, the list may also include 121 // additional packages that are not strictly required for 122 // import processing alone (they are exported to err "on 123 // the safe side"). 124 got := fmt.Sprint(pkg.Imports()) 125 for _, want := range []string{"go/ast", "go/token"} { 126 if !strings.Contains(got, want) { 127 t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want) 128 } 129 } 130 } 131 } 132 133 // TODO(gri) Remove this function once we switched to new export format by default 134 // (and update the comment and want list in TestImportTestdata). 135 func TestImportTestdataNewExport(t *testing.T) { 136 // This package only handles gc export data. 137 if runtime.Compiler != "gc" { 138 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 139 return 140 } 141 142 if outFn := compileNewExport(t, "testdata", "exports.go"); outFn != "" { 143 defer os.Remove(outFn) 144 } 145 146 if pkg := testPath(t, "./testdata/exports"); pkg != nil { 147 // The package's Imports list must include all packages 148 // explicitly imported by exports.go, plus all packages 149 // referenced indirectly via exported objects in exports.go. 150 want := `[package ast ("go/ast") package token ("go/token")]` 151 got := fmt.Sprint(pkg.Imports()) 152 if got != want { 153 t.Errorf(`Package("exports").Imports() = %s, want %s`, got, want) 154 } 155 } 156 } 157 158 func TestImportStdLib(t *testing.T) { 159 skipSpecialPlatforms(t) 160 161 // This package only handles gc export data. 162 if runtime.Compiler != "gc" { 163 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 164 return 165 } 166 167 nimports := testDir(t, "", time.Now().Add(maxTime)) // installed packages 168 t.Logf("tested %d imports", nimports) 169 } 170 171 var importedObjectTests = []struct { 172 name string 173 want string 174 }{ 175 {"math.Pi", "const Pi untyped float"}, 176 {"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"}, 177 {"io.ReadWriter", "type ReadWriter interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"}, 178 {"math.Sin", "func Sin(x float64) float64"}, 179 // TODO(gri) add more tests 180 } 181 182 func TestImportedTypes(t *testing.T) { 183 skipSpecialPlatforms(t) 184 185 // This package only handles gc export data. 186 if runtime.Compiler != "gc" { 187 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 188 return 189 } 190 191 for _, test := range importedObjectTests { 192 s := strings.Split(test.name, ".") 193 if len(s) != 2 { 194 t.Fatal("inconsistent test data") 195 } 196 importPath := s[0] 197 objName := s[1] 198 199 pkg, err := Import(make(map[string]*types.Package), importPath) 200 if err != nil { 201 t.Error(err) 202 continue 203 } 204 205 obj := pkg.Scope().Lookup(objName) 206 if obj == nil { 207 t.Errorf("%s: object not found", test.name) 208 continue 209 } 210 211 got := types.ObjectString(obj, types.RelativeTo(pkg)) 212 if got != test.want { 213 t.Errorf("%s: got %q; want %q", test.name, got, test.want) 214 } 215 } 216 } 217 218 func TestIssue5815(t *testing.T) { 219 skipSpecialPlatforms(t) 220 221 // This package only handles gc export data. 222 if runtime.Compiler != "gc" { 223 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 224 return 225 } 226 227 pkg, err := Import(make(map[string]*types.Package), "strings") 228 if err != nil { 229 t.Fatal(err) 230 } 231 232 scope := pkg.Scope() 233 for _, name := range scope.Names() { 234 obj := scope.Lookup(name) 235 if obj.Pkg() == nil { 236 t.Errorf("no pkg for %s", obj) 237 } 238 if tname, _ := obj.(*types.TypeName); tname != nil { 239 named := tname.Type().(*types.Named) 240 for i := 0; i < named.NumMethods(); i++ { 241 m := named.Method(i) 242 if m.Pkg() == nil { 243 t.Errorf("no pkg for %s", m) 244 } 245 } 246 } 247 } 248 } 249 250 // Smoke test to ensure that imported methods get the correct package. 251 func TestCorrectMethodPackage(t *testing.T) { 252 skipSpecialPlatforms(t) 253 254 // This package only handles gc export data. 255 if runtime.Compiler != "gc" { 256 t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler) 257 return 258 } 259 260 imports := make(map[string]*types.Package) 261 _, err := Import(imports, "net/http") 262 if err != nil { 263 t.Fatal(err) 264 } 265 266 mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type() 267 mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex 268 sel := mset.Lookup(nil, "Lock") 269 lock := sel.Obj().(*types.Func) 270 if got, want := lock.Pkg().Path(), "sync"; got != want { 271 t.Errorf("got package path %q; want %q", got, want) 272 } 273 }