summaryrefslogtreecommitdiff
path: root/src/go/internal/srcimporter/srcimporter_test.go
blob: 79921b5e7855bd0ba46f1541baa137a6fe493aaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package srcimporter

import (
	"go/build"
	"go/token"
	"go/types"
	"internal/testenv"
	"io/ioutil"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
	"time"
)

const maxTime = 2 * time.Second

var importer = New(&build.Default, token.NewFileSet(), make(map[string]*types.Package))

func doImport(t *testing.T, path, srcDir string) {
	t0 := time.Now()
	if _, err := importer.ImportFrom(path, srcDir, 0); err != nil {
		// don't report an error if there's no buildable Go files
		if _, nogo := err.(*build.NoGoError); !nogo {
			t.Errorf("import %q failed (%v)", path, err)
		}
		return
	}
	t.Logf("import %q: %v", path, time.Since(t0))
}

// walkDir imports the all the packages with the given path
// prefix recursively. It returns the number of packages
// imported and whether importing was aborted because time
// has passed endTime.
func walkDir(t *testing.T, path string, endTime time.Time) (int, bool) {
	if time.Now().After(endTime) {
		t.Log("testing time used up")
		return 0, true
	}

	// ignore fake packages and testdata directories
	if path == "builtin" || path == "unsafe" || strings.HasSuffix(path, "testdata") {
		return 0, false
	}

	list, err := ioutil.ReadDir(filepath.Join(runtime.GOROOT(), "src", path))
	if err != nil {
		t.Fatalf("walkDir %s failed (%v)", path, err)
	}

	nimports := 0
	hasGoFiles := false
	for _, f := range list {
		if f.IsDir() {
			n, abort := walkDir(t, filepath.Join(path, f.Name()), endTime)
			nimports += n
			if abort {
				return nimports, true
			}
		} else if strings.HasSuffix(f.Name(), ".go") {
			hasGoFiles = true
		}
	}

	if hasGoFiles {
		doImport(t, path, "")
		nimports++
	}

	return nimports, false
}

func TestImportStdLib(t *testing.T) {
	if !testenv.HasSrc() {
		t.Skip("no source code available")
	}

	dt := maxTime
	if testing.Short() && testenv.Builder() == "" {
		dt = 500 * time.Millisecond
	}
	nimports, _ := walkDir(t, "", time.Now().Add(dt)) // installed packages
	t.Logf("tested %d imports", nimports)
}

var importedObjectTests = []struct {
	name string
	want string
}{
	{"flag.Bool", "func Bool(name string, value bool, usage string) *bool"},
	{"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
	{"io.ReadWriter", "type ReadWriter interface{Reader; Writer}"}, // go/types.gcCompatibilityMode is off => interface not flattened
	{"math.Pi", "const Pi untyped float"},
	{"math.Sin", "func Sin(x float64) float64"},
	{"math/big.Int", "type Int struct{neg bool; abs nat}"},
	{"golang_org/x/text/unicode/norm.MaxSegmentSize", "const MaxSegmentSize untyped int"},
}

func TestImportedTypes(t *testing.T) {
	if !testenv.HasSrc() {
		t.Skip("no source code available")
	}

	for _, test := range importedObjectTests {
		s := strings.Split(test.name, ".")
		if len(s) != 2 {
			t.Fatal("invalid test data format")
		}
		importPath := s[0]
		objName := s[1]

		pkg, err := importer.ImportFrom(importPath, ".", 0)
		if err != nil {
			t.Error(err)
			continue
		}

		obj := pkg.Scope().Lookup(objName)
		if obj == nil {
			t.Errorf("%s: object not found", test.name)
			continue
		}

		got := types.ObjectString(obj, types.RelativeTo(pkg))
		if got != test.want {
			t.Errorf("%s: got %q; want %q", test.name, got, test.want)
		}
	}
}

func TestReimport(t *testing.T) {
	if !testenv.HasSrc() {
		t.Skip("no source code available")
	}

	// Reimporting a partially imported (incomplete) package is not supported (see issue #19337).
	// Make sure we recognize the situation and report an error.

	mathPkg := types.NewPackage("math", "math") // incomplete package
	importer := New(&build.Default, token.NewFileSet(), map[string]*types.Package{mathPkg.Path(): mathPkg})
	_, err := importer.ImportFrom("math", ".", 0)
	if err == nil || !strings.HasPrefix(err.Error(), "reimport") {
		t.Errorf("got %v; want reimport error", err)
	}
}