github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/go/importer/importer_test.go (about) 1 // Copyright 2017 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 importer 6 7 import ( 8 "go/token" 9 "internal/testenv" 10 "io" 11 "io/ioutil" 12 "os" 13 "os/exec" 14 "runtime" 15 "strings" 16 "testing" 17 ) 18 19 func TestForCompiler(t *testing.T) { 20 testenv.MustHaveGoBuild(t) 21 22 const thePackage = "math/big" 23 out, err := exec.Command(testenv.GoToolPath(t), "list", "-f={{context.Compiler}}:{{.Target}}", thePackage).CombinedOutput() 24 if err != nil { 25 t.Fatalf("go list %s: %v\n%s", thePackage, err, out) 26 } 27 target := strings.TrimSpace(string(out)) 28 i := strings.Index(target, ":") 29 compiler, target := target[:i], target[i+1:] 30 if !strings.HasSuffix(target, ".a") { 31 t.Fatalf("unexpected package %s target %q (not *.a)", thePackage, target) 32 } 33 34 if compiler == "gccgo" { 35 t.Skip("golang.org/issue/22500") 36 } 37 38 fset := token.NewFileSet() 39 40 t.Run("LookupDefault", func(t *testing.T) { 41 imp := ForCompiler(fset, compiler, nil) 42 pkg, err := imp.Import(thePackage) 43 if err != nil { 44 t.Fatal(err) 45 } 46 if pkg.Path() != thePackage { 47 t.Fatalf("Path() = %q, want %q", pkg.Path(), thePackage) 48 } 49 50 // Check that the fileset positions are accurate. 51 // https://github.com/golang/go#28995 52 mathBigInt := pkg.Scope().Lookup("Int") 53 posn := fset.Position(mathBigInt.Pos()) // "$GOROOT/src/math/big/int.go:25:1" 54 filename := strings.Replace(posn.Filename, "$GOROOT", runtime.GOROOT(), 1) 55 data, err := ioutil.ReadFile(filename) 56 if err != nil { 57 t.Fatalf("can't read file containing declaration of math/big.Int: %v", err) 58 } 59 lines := strings.Split(string(data), "\n") 60 if posn.Line > len(lines) || !strings.HasPrefix(lines[posn.Line-1], "type Int") { 61 t.Fatalf("Object %v position %s does not contain its declaration", 62 mathBigInt, posn) 63 } 64 }) 65 66 t.Run("LookupCustom", func(t *testing.T) { 67 lookup := func(path string) (io.ReadCloser, error) { 68 if path != "math/bigger" { 69 t.Fatalf("lookup called with unexpected path %q", path) 70 } 71 f, err := os.Open(target) 72 if err != nil { 73 t.Fatal(err) 74 } 75 return f, nil 76 } 77 imp := ForCompiler(fset, compiler, lookup) 78 pkg, err := imp.Import("math/bigger") 79 if err != nil { 80 t.Fatal(err) 81 } 82 // Even though we open math/big.a, the import request was for math/bigger 83 // and that should be recorded in pkg.Path(), at least for the gc toolchain. 84 if pkg.Path() != "math/bigger" { 85 t.Fatalf("Path() = %q, want %q", pkg.Path(), "math/bigger") 86 } 87 }) 88 }