github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/x/tools/go/gcimporter15/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  // +build go1.5
     6  
     7  // This file is a copy of $GOROOT/src/go/internal/gcimporter/gcimporter_test.go, tagged for go1.5,
     8  // and minimally adjusted to make it build with code from (std lib) internal/testenv copied.
     9  
    10  package gcimporter
    11  
    12  import (
    13  	"fmt"
    14  	"go/types"
    15  	"io/ioutil"
    16  	"os"
    17  	"os/exec"
    18  	"path/filepath"
    19  	"runtime"
    20  	"strings"
    21  	"testing"
    22  	"time"
    23  )
    24  
    25  // ----------------------------------------------------------------------------
    26  // The following three functions (Builder, HasGoBuild, MustHaveGoBuild) were
    27  // copied from $GOROOT/src/internal/testenv since that package is not available
    28  // in x/tools.
    29  
    30  // Builder reports the name of the builder running this test
    31  // (for example, "linux-amd64" or "windows-386-gce").
    32  // If the test is not running on the build infrastructure,
    33  // Builder returns the empty string.
    34  func Builder() string {
    35  	return os.Getenv("GO_BUILDER_NAME")
    36  }
    37  
    38  // HasGoBuild reports whether the current system can build programs with ``go build''
    39  // and then run them with os.StartProcess or exec.Command.
    40  func HasGoBuild() bool {
    41  	switch runtime.GOOS {
    42  	case "android", "nacl":
    43  		return false
    44  	case "darwin":
    45  		if strings.HasPrefix(runtime.GOARCH, "arm") {
    46  			return false
    47  		}
    48  	}
    49  	return true
    50  }
    51  
    52  // MustHaveGoBuild checks that the current system can build programs with ``go build''
    53  // and then run them with os.StartProcess or exec.Command.
    54  // If not, MustHaveGoBuild calls t.Skip with an explanation.
    55  func MustHaveGoBuild(t *testing.T) {
    56  	if !HasGoBuild() {
    57  		t.Skipf("skipping test: 'go build' not available on %s/%s", runtime.GOOS, runtime.GOARCH)
    58  	}
    59  }
    60  
    61  // ----------------------------------------------------------------------------
    62  
    63  // skipSpecialPlatforms causes the test to be skipped for platforms where
    64  // builders (build.golang.org) don't have access to compiled packages for
    65  // import.
    66  func skipSpecialPlatforms(t *testing.T) {
    67  	switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform {
    68  	case "nacl-amd64p32",
    69  		"nacl-386",
    70  		"nacl-arm",
    71  		"darwin-arm",
    72  		"darwin-arm64":
    73  		t.Skipf("no compiled packages available for import on %s", platform)
    74  	}
    75  }
    76  
    77  func compile(t *testing.T, dirname, filename string) string {
    78  	/* testenv. */ MustHaveGoBuild(t)
    79  	cmd := exec.Command("go", "tool", "compile", filename)
    80  	cmd.Dir = dirname
    81  	out, err := cmd.CombinedOutput()
    82  	if err != nil {
    83  		t.Logf("%s", out)
    84  		t.Fatalf("go tool compile %s failed: %s", filename, err)
    85  	}
    86  	// filename should end with ".go"
    87  	return filepath.Join(dirname, filename[:len(filename)-2]+"o")
    88  }
    89  
    90  func testPath(t *testing.T, path, srcDir string) *types.Package {
    91  	t0 := time.Now()
    92  	pkg, err := Import(make(map[string]*types.Package), path, srcDir)
    93  	if err != nil {
    94  		t.Errorf("testPath(%s): %s", path, err)
    95  		return nil
    96  	}
    97  	t.Logf("testPath(%s): %v", path, time.Since(t0))
    98  	return pkg
    99  }
   100  
   101  const maxTime = 30 * time.Second
   102  
   103  func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
   104  	dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
   105  	list, err := ioutil.ReadDir(dirname)
   106  	if err != nil {
   107  		t.Fatalf("testDir(%s): %s", dirname, err)
   108  	}
   109  	for _, f := range list {
   110  		if time.Now().After(endTime) {
   111  			t.Log("testing time used up")
   112  			return
   113  		}
   114  		switch {
   115  		case !f.IsDir():
   116  			// try extensions
   117  			for _, ext := range pkgExts {
   118  				if strings.HasSuffix(f.Name(), ext) {
   119  					name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension
   120  					if testPath(t, filepath.Join(dir, name), dir) != nil {
   121  						nimports++
   122  					}
   123  				}
   124  			}
   125  		case f.IsDir():
   126  			nimports += testDir(t, filepath.Join(dir, f.Name()), endTime)
   127  		}
   128  	}
   129  	return
   130  }
   131  
   132  func TestImportTestdata(t *testing.T) {
   133  	// This package only handles gc export data.
   134  	if runtime.Compiler != "gc" {
   135  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   136  		return
   137  	}
   138  
   139  	if outFn := compile(t, "testdata", "exports.go"); outFn != "" {
   140  		defer os.Remove(outFn)
   141  	}
   142  
   143  	if pkg := testPath(t, "./testdata/exports", "."); pkg != nil {
   144  		// The package's Imports list must include all packages
   145  		// explicitly imported by exports.go, plus all packages
   146  		// referenced indirectly via exported objects in exports.go.
   147  		// With the textual export format, the list may also include
   148  		// additional packages that are not strictly required for
   149  		// import processing alone (they are exported to err "on
   150  		// the safe side").
   151  		got := fmt.Sprint(pkg.Imports())
   152  		for _, want := range []string{"go/ast", "go/token"} {
   153  			if !strings.Contains(got, want) {
   154  				t.Errorf(`Package("exports").Imports() = %s, does not contain %s`, got, want)
   155  			}
   156  		}
   157  	}
   158  }
   159  
   160  func TestImportStdLib(t *testing.T) {
   161  	skipSpecialPlatforms(t)
   162  
   163  	// This package only handles gc export data.
   164  	if runtime.Compiler != "gc" {
   165  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   166  		return
   167  	}
   168  
   169  	dt := maxTime
   170  	if testing.Short() && /* testenv. */ Builder() == "" {
   171  		dt = 10 * time.Millisecond
   172  	}
   173  	nimports := testDir(t, "", time.Now().Add(dt)) // installed packages
   174  	t.Logf("tested %d imports", nimports)
   175  }
   176  
   177  var importedObjectTests = []struct {
   178  	name string
   179  	want string
   180  }{
   181  	{"math.Pi", "const Pi untyped float"},
   182  	{"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
   183  	{"io.ReadWriter", "type ReadWriter interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"},
   184  	{"math.Sin", "func Sin(x float64) float64"},
   185  	// TODO(gri) add more tests
   186  }
   187  
   188  func TestImportedTypes(t *testing.T) {
   189  	skipSpecialPlatforms(t)
   190  
   191  	// This package only handles gc export data.
   192  	if runtime.Compiler != "gc" {
   193  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   194  		return
   195  	}
   196  
   197  	for _, test := range importedObjectTests {
   198  		s := strings.Split(test.name, ".")
   199  		if len(s) != 2 {
   200  			t.Fatal("inconsistent test data")
   201  		}
   202  		importPath := s[0]
   203  		objName := s[1]
   204  
   205  		pkg, err := Import(make(map[string]*types.Package), importPath, ".")
   206  		if err != nil {
   207  			t.Error(err)
   208  			continue
   209  		}
   210  
   211  		obj := pkg.Scope().Lookup(objName)
   212  		if obj == nil {
   213  			t.Errorf("%s: object not found", test.name)
   214  			continue
   215  		}
   216  
   217  		got := types.ObjectString(obj, types.RelativeTo(pkg))
   218  		if got != test.want {
   219  			t.Errorf("%s: got %q; want %q", test.name, got, test.want)
   220  		}
   221  	}
   222  }
   223  
   224  func TestIssue5815(t *testing.T) {
   225  	skipSpecialPlatforms(t)
   226  
   227  	// This package only handles gc export data.
   228  	if runtime.Compiler != "gc" {
   229  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   230  		return
   231  	}
   232  
   233  	pkg, err := Import(make(map[string]*types.Package), "strings", ".")
   234  	if err != nil {
   235  		t.Fatal(err)
   236  	}
   237  
   238  	scope := pkg.Scope()
   239  	for _, name := range scope.Names() {
   240  		obj := scope.Lookup(name)
   241  		if obj.Pkg() == nil {
   242  			t.Errorf("no pkg for %s", obj)
   243  		}
   244  		if tname, _ := obj.(*types.TypeName); tname != nil {
   245  			named := tname.Type().(*types.Named)
   246  			for i := 0; i < named.NumMethods(); i++ {
   247  				m := named.Method(i)
   248  				if m.Pkg() == nil {
   249  					t.Errorf("no pkg for %s", m)
   250  				}
   251  			}
   252  		}
   253  	}
   254  }
   255  
   256  // Smoke test to ensure that imported methods get the correct package.
   257  func TestCorrectMethodPackage(t *testing.T) {
   258  	skipSpecialPlatforms(t)
   259  
   260  	// This package only handles gc export data.
   261  	if runtime.Compiler != "gc" {
   262  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   263  		return
   264  	}
   265  
   266  	imports := make(map[string]*types.Package)
   267  	_, err := Import(imports, "net/http", ".")
   268  	if err != nil {
   269  		t.Fatal(err)
   270  	}
   271  
   272  	mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type()
   273  	mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex
   274  	sel := mset.Lookup(nil, "Lock")
   275  	lock := sel.Obj().(*types.Func)
   276  	if got, want := lock.Pkg().Path(), "sync"; got != want {
   277  		t.Errorf("got package path %q; want %q", got, want)
   278  	}
   279  }
   280  
   281  func TestIssue13566(t *testing.T) {
   282  	skipSpecialPlatforms(t)
   283  
   284  	// This package only handles gc export data.
   285  	if runtime.Compiler != "gc" {
   286  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   287  		return
   288  	}
   289  
   290  	// On windows, we have to set the -D option for the compiler to avoid having a drive
   291  	// letter and an illegal ':' in the import path - just skip it (see also issue #3483).
   292  	if runtime.GOOS == "windows" {
   293  		t.Skip("avoid dealing with relative paths/drive letters on windows")
   294  	}
   295  
   296  	if f := compile(t, "testdata", "a.go"); f != "" {
   297  		defer os.Remove(f)
   298  	}
   299  	if f := compile(t, "testdata", "b.go"); f != "" {
   300  		defer os.Remove(f)
   301  	}
   302  
   303  	// import must succeed (test for issue at hand)
   304  	pkg, err := Import(make(map[string]*types.Package), "./testdata/b", ".")
   305  	if err != nil {
   306  		t.Fatal(err)
   307  	}
   308  
   309  	// make sure all indirectly imported packages have names
   310  	for _, imp := range pkg.Imports() {
   311  		if imp.Name() == "" {
   312  			t.Errorf("no name for %s package", imp.Path())
   313  		}
   314  	}
   315  }
   316  
   317  func TestIssue13898(t *testing.T) {
   318  	skipSpecialPlatforms(t)
   319  
   320  	// This package only handles gc export data.
   321  	if runtime.Compiler != "gc" {
   322  		t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
   323  		return
   324  	}
   325  
   326  	// import go/internal/gcimporter which imports go/types partially
   327  	imports := make(map[string]*types.Package)
   328  	_, err := Import(imports, "go/internal/gcimporter", ".")
   329  	if err != nil {
   330  		t.Fatal(err)
   331  	}
   332  
   333  	// look for go/types package
   334  	var goTypesPkg *types.Package
   335  	for path, pkg := range imports {
   336  		if path == "go/types" {
   337  			goTypesPkg = pkg
   338  			break
   339  		}
   340  	}
   341  	if goTypesPkg == nil {
   342  		t.Fatal("go/types not found")
   343  	}
   344  
   345  	// look for go/types.Object type
   346  	obj := goTypesPkg.Scope().Lookup("Object")
   347  	if obj == nil {
   348  		t.Fatal("go/types.Object not found")
   349  	}
   350  	typ, ok := obj.Type().(*types.Named)
   351  	if !ok {
   352  		t.Fatalf("go/types.Object type is %v; wanted named type", typ)
   353  	}
   354  
   355  	// lookup go/types.Object.Pkg method
   356  	m, _, _ := types.LookupFieldOrMethod(typ, false, nil, "Pkg")
   357  	if m == nil {
   358  		t.Fatal("go/types.Object.Pkg not found")
   359  	}
   360  
   361  	// the method must belong to go/types
   362  	if m.Pkg().Path() != "go/types" {
   363  		t.Fatalf("found %v; want go/types", m.Pkg())
   364  	}
   365  }