Source file
src/go/importer/importer_test.go
1
2
3
4
5 package importer
6
7 import (
8 "go/build"
9 "go/token"
10 "internal/testenv"
11 "io"
12 "os"
13 "strings"
14 "testing"
15 )
16
17 func TestMain(m *testing.M) {
18 build.Default.GOROOT = testenv.GOROOT(nil)
19 os.Exit(m.Run())
20 }
21
22 func TestForCompiler(t *testing.T) {
23 testenv.MustHaveGoBuild(t)
24
25 const thePackage = "math/big"
26 out, err := testenv.Command(t, testenv.GoToolPath(t), "list", "-export", "-f={{context.Compiler}}:{{.Export}}", thePackage).CombinedOutput()
27 if err != nil {
28 t.Fatalf("go list %s: %v\n%s", thePackage, err, out)
29 }
30 export := strings.TrimSpace(string(out))
31 compiler, target, _ := strings.Cut(export, ":")
32
33 if compiler == "gccgo" {
34 t.Skip("golang.org/issue/22500")
35 }
36
37 fset := token.NewFileSet()
38
39 t.Run("LookupDefault", func(t *testing.T) {
40 imp := ForCompiler(fset, compiler, nil)
41 pkg, err := imp.Import(thePackage)
42 if err != nil {
43 t.Fatal(err)
44 }
45 if pkg.Path() != thePackage {
46 t.Fatalf("Path() = %q, want %q", pkg.Path(), thePackage)
47 }
48
49
50
51 mathBigInt := pkg.Scope().Lookup("Int")
52 posn := fset.Position(mathBigInt.Pos())
53 filename := strings.Replace(posn.Filename, "$GOROOT", testenv.GOROOT(t), 1)
54 data, err := os.ReadFile(filename)
55 if err != nil {
56 t.Fatalf("can't read file containing declaration of math/big.Int: %v", err)
57 }
58 lines := strings.Split(string(data), "\n")
59 if posn.Line > len(lines) || !strings.HasPrefix(lines[posn.Line-1], "type Int") {
60 t.Fatalf("Object %v position %s does not contain its declaration",
61 mathBigInt, posn)
62 }
63 })
64
65 t.Run("LookupCustom", func(t *testing.T) {
66
67
68
69
70 if true {
71 t.Skip("not supported by GOEXPERIMENT=unified; see go.dev/cl/406319")
72 }
73
74 lookup := func(path string) (io.ReadCloser, error) {
75 if path != "math/bigger" {
76 t.Fatalf("lookup called with unexpected path %q", path)
77 }
78 f, err := os.Open(target)
79 if err != nil {
80 t.Fatal(err)
81 }
82 return f, nil
83 }
84 imp := ForCompiler(fset, compiler, lookup)
85 pkg, err := imp.Import("math/bigger")
86 if err != nil {
87 t.Fatal(err)
88 }
89
90
91 if pkg.Path() != "math/bigger" {
92 t.Fatalf("Path() = %q, want %q", pkg.Path(), "math/bigger")
93 }
94 })
95 }
96
View as plain text