github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/go/types/stdlib_test.go (about)

     1  // Copyright 2013 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  // This file tests types.Check by using it to
     6  // typecheck the standard library and tests.
     7  
     8  package types_test
     9  
    10  import (
    11  	"fmt"
    12  	"go/ast"
    13  	"go/build"
    14  	"go/importer"
    15  	"go/parser"
    16  	"go/scanner"
    17  	"go/token"
    18  	"internal/testenv"
    19  	"io/ioutil"
    20  	"os"
    21  	"path/filepath"
    22  	"runtime"
    23  	"strings"
    24  	"testing"
    25  	"time"
    26  
    27  	. "go/types"
    28  )
    29  
    30  var (
    31  	pkgCount int // number of packages processed
    32  	start    time.Time
    33  
    34  	// Use the same importer for all std lib tests to
    35  	// avoid repeated importing of the same packages.
    36  	stdLibImporter = importer.Default()
    37  )
    38  
    39  func TestStdlib(t *testing.T) {
    40  	testenv.MustHaveGoBuild(t)
    41  
    42  	start = time.Now()
    43  	walkDirs(t, filepath.Join(runtime.GOROOT(), "src"))
    44  	if testing.Verbose() {
    45  		fmt.Println(pkgCount, "packages typechecked in", time.Since(start))
    46  	}
    47  }
    48  
    49  // firstComment returns the contents of the first comment in
    50  // the given file, assuming there's one within the first KB.
    51  func firstComment(filename string) string {
    52  	f, err := os.Open(filename)
    53  	if err != nil {
    54  		return ""
    55  	}
    56  	defer f.Close()
    57  
    58  	var src [1 << 10]byte // read at most 1KB
    59  	n, _ := f.Read(src[:])
    60  
    61  	var s scanner.Scanner
    62  	s.Init(fset.AddFile("", fset.Base(), n), src[:n], nil, scanner.ScanComments)
    63  	for {
    64  		_, tok, lit := s.Scan()
    65  		switch tok {
    66  		case token.COMMENT:
    67  			// remove trailing */ of multi-line comment
    68  			if lit[1] == '*' {
    69  				lit = lit[:len(lit)-2]
    70  			}
    71  			return strings.TrimSpace(lit[2:])
    72  		case token.EOF:
    73  			return ""
    74  		}
    75  	}
    76  }
    77  
    78  func testTestDir(t *testing.T, path string, ignore ...string) {
    79  	files, err := ioutil.ReadDir(path)
    80  	if err != nil {
    81  		t.Fatal(err)
    82  	}
    83  
    84  	excluded := make(map[string]bool)
    85  	for _, filename := range ignore {
    86  		excluded[filename] = true
    87  	}
    88  
    89  	fset := token.NewFileSet()
    90  	for _, f := range files {
    91  		// filter directory contents
    92  		if f.IsDir() || !strings.HasSuffix(f.Name(), ".go") || excluded[f.Name()] {
    93  			continue
    94  		}
    95  
    96  		// get per-file instructions
    97  		expectErrors := false
    98  		filename := filepath.Join(path, f.Name())
    99  		if cmd := firstComment(filename); cmd != "" {
   100  			switch cmd {
   101  			case "skip", "compiledir":
   102  				continue // ignore this file
   103  			case "errorcheck":
   104  				expectErrors = true
   105  			}
   106  		}
   107  
   108  		// parse and type-check file
   109  		file, err := parser.ParseFile(fset, filename, nil, 0)
   110  		if err == nil {
   111  			conf := Config{Importer: stdLibImporter}
   112  			_, err = conf.Check(filename, fset, []*ast.File{file}, nil)
   113  		}
   114  
   115  		if expectErrors {
   116  			if err == nil {
   117  				t.Errorf("expected errors but found none in %s", filename)
   118  			}
   119  		} else {
   120  			if err != nil {
   121  				t.Error(err)
   122  			}
   123  		}
   124  	}
   125  }
   126  
   127  func TestStdTest(t *testing.T) {
   128  	testenv.MustHaveGoBuild(t)
   129  
   130  	if testing.Short() && testenv.Builder() == "" {
   131  		t.Skip("skipping in short mode")
   132  	}
   133  
   134  	// test/recover4.go is only built for Linux and Darwin.
   135  	// TODO(gri) Remove once tests consider +build tags (issue 10370).
   136  	if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
   137  		return
   138  	}
   139  
   140  	testTestDir(t, filepath.Join(runtime.GOROOT(), "test"),
   141  		"cmplxdivide.go", // also needs file cmplxdivide1.go - ignore
   142  		"sigchld.go",     // don't work on Windows; testTestDir should consult build tags
   143  	)
   144  }
   145  
   146  func TestStdFixed(t *testing.T) {
   147  	testenv.MustHaveGoBuild(t)
   148  
   149  	if testing.Short() && testenv.Builder() == "" {
   150  		t.Skip("skipping in short mode")
   151  	}
   152  
   153  	testTestDir(t, filepath.Join(runtime.GOROOT(), "test", "fixedbugs"),
   154  		"bug248.go", "bug302.go", "bug369.go", // complex test instructions - ignore
   155  		"issue6889.go",  // gc-specific test
   156  		"issue7746.go",  // large constants - consumes too much memory
   157  		"issue11362.go", // canonical import path check
   158  		"issue15002.go", // uses Mmap; testTestDir should consult build tags
   159  		"issue16369.go", // go/types handles this correctly - not an issue
   160  	)
   161  }
   162  
   163  func TestStdKen(t *testing.T) {
   164  	testenv.MustHaveGoBuild(t)
   165  
   166  	testTestDir(t, filepath.Join(runtime.GOROOT(), "test", "ken"))
   167  }
   168  
   169  // Package paths of excluded packages.
   170  var excluded = map[string]bool{
   171  	"builtin": true,
   172  }
   173  
   174  // typecheck typechecks the given package files.
   175  func typecheck(t *testing.T, path string, filenames []string) {
   176  	fset := token.NewFileSet()
   177  
   178  	// parse package files
   179  	var files []*ast.File
   180  	for _, filename := range filenames {
   181  		file, err := parser.ParseFile(fset, filename, nil, parser.AllErrors)
   182  		if err != nil {
   183  			// the parser error may be a list of individual errors; report them all
   184  			if list, ok := err.(scanner.ErrorList); ok {
   185  				for _, err := range list {
   186  					t.Error(err)
   187  				}
   188  				return
   189  			}
   190  			t.Error(err)
   191  			return
   192  		}
   193  
   194  		if testing.Verbose() {
   195  			if len(files) == 0 {
   196  				fmt.Println("package", file.Name.Name)
   197  			}
   198  			fmt.Println("\t", filename)
   199  		}
   200  
   201  		files = append(files, file)
   202  	}
   203  
   204  	// typecheck package files
   205  	conf := Config{
   206  		Error:    func(err error) { t.Error(err) },
   207  		Importer: stdLibImporter,
   208  	}
   209  	info := Info{Uses: make(map[*ast.Ident]Object)}
   210  	conf.Check(path, fset, files, &info)
   211  	pkgCount++
   212  
   213  	// Perform checks of API invariants.
   214  
   215  	// All Objects have a package, except predeclared ones.
   216  	errorError := Universe.Lookup("error").Type().Underlying().(*Interface).ExplicitMethod(0) // (error).Error
   217  	for id, obj := range info.Uses {
   218  		predeclared := obj == Universe.Lookup(obj.Name()) || obj == errorError
   219  		if predeclared == (obj.Pkg() != nil) {
   220  			posn := fset.Position(id.Pos())
   221  			if predeclared {
   222  				t.Errorf("%s: predeclared object with package: %s", posn, obj)
   223  			} else {
   224  				t.Errorf("%s: user-defined object without package: %s", posn, obj)
   225  			}
   226  		}
   227  	}
   228  }
   229  
   230  // pkgFilenames returns the list of package filenames for the given directory.
   231  func pkgFilenames(dir string) ([]string, error) {
   232  	ctxt := build.Default
   233  	ctxt.CgoEnabled = false
   234  	pkg, err := ctxt.ImportDir(dir, 0)
   235  	if err != nil {
   236  		if _, nogo := err.(*build.NoGoError); nogo {
   237  			return nil, nil // no *.go files, not an error
   238  		}
   239  		return nil, err
   240  	}
   241  	if excluded[pkg.ImportPath] {
   242  		return nil, nil
   243  	}
   244  	var filenames []string
   245  	for _, name := range pkg.GoFiles {
   246  		filenames = append(filenames, filepath.Join(pkg.Dir, name))
   247  	}
   248  	for _, name := range pkg.TestGoFiles {
   249  		filenames = append(filenames, filepath.Join(pkg.Dir, name))
   250  	}
   251  	return filenames, nil
   252  }
   253  
   254  // Note: Could use filepath.Walk instead of walkDirs but that wouldn't
   255  //       necessarily be shorter or clearer after adding the code to
   256  //       terminate early for -short tests.
   257  
   258  func walkDirs(t *testing.T, dir string) {
   259  	// limit run time for short tests
   260  	if testing.Short() && time.Since(start) >= 10*time.Millisecond {
   261  		return
   262  	}
   263  
   264  	fis, err := ioutil.ReadDir(dir)
   265  	if err != nil {
   266  		t.Error(err)
   267  		return
   268  	}
   269  
   270  	// typecheck package in directory
   271  	// but ignore files directly under $GOROOT/src (might be temporary test files).
   272  	if dir != filepath.Join(runtime.GOROOT(), "src") {
   273  		files, err := pkgFilenames(dir)
   274  		if err != nil {
   275  			t.Error(err)
   276  			return
   277  		}
   278  		if files != nil {
   279  			typecheck(t, dir, files)
   280  		}
   281  	}
   282  
   283  	// traverse subdirectories, but don't walk into testdata
   284  	for _, fi := range fis {
   285  		if fi.IsDir() && fi.Name() != "testdata" {
   286  			walkDirs(t, filepath.Join(dir, fi.Name()))
   287  		}
   288  	}
   289  }