github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/go/build/build_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  package build
     6  
     7  import (
     8  	"internal/testenv"
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  	"reflect"
    13  	"runtime"
    14  	"strings"
    15  	"testing"
    16  )
    17  
    18  func TestMatch(t *testing.T) {
    19  	ctxt := Default
    20  	what := "default"
    21  	match := func(tag string, want map[string]bool) {
    22  		m := make(map[string]bool)
    23  		if !ctxt.match(tag, m) {
    24  			t.Errorf("%s context should match %s, does not", what, tag)
    25  		}
    26  		if !reflect.DeepEqual(m, want) {
    27  			t.Errorf("%s tags = %v, want %v", tag, m, want)
    28  		}
    29  	}
    30  	nomatch := func(tag string, want map[string]bool) {
    31  		m := make(map[string]bool)
    32  		if ctxt.match(tag, m) {
    33  			t.Errorf("%s context should NOT match %s, does", what, tag)
    34  		}
    35  		if !reflect.DeepEqual(m, want) {
    36  			t.Errorf("%s tags = %v, want %v", tag, m, want)
    37  		}
    38  	}
    39  
    40  	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
    41  	match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
    42  	nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
    43  
    44  	what = "modified"
    45  	ctxt.BuildTags = []string{"foo"}
    46  	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
    47  	match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
    48  	nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
    49  	match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
    50  	nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
    51  	nomatch("!", map[string]bool{})
    52  }
    53  
    54  func TestDotSlashImport(t *testing.T) {
    55  	p, err := ImportDir("testdata/other", 0)
    56  	if err != nil {
    57  		t.Fatal(err)
    58  	}
    59  	if len(p.Imports) != 1 || p.Imports[0] != "./file" {
    60  		t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports)
    61  	}
    62  
    63  	p1, err := Import("./file", "testdata/other", 0)
    64  	if err != nil {
    65  		t.Fatal(err)
    66  	}
    67  	if p1.Name != "file" {
    68  		t.Fatalf("./file: Name=%q, want %q", p1.Name, "file")
    69  	}
    70  	dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows
    71  	if p1.Dir != dir {
    72  		t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir)
    73  	}
    74  }
    75  
    76  func TestEmptyImport(t *testing.T) {
    77  	p, err := Import("", Default.GOROOT, FindOnly)
    78  	if err == nil {
    79  		t.Fatal(`Import("") returned nil error.`)
    80  	}
    81  	if p == nil {
    82  		t.Fatal(`Import("") returned nil package.`)
    83  	}
    84  	if p.ImportPath != "" {
    85  		t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "")
    86  	}
    87  }
    88  
    89  func TestEmptyFolderImport(t *testing.T) {
    90  	_, err := Import(".", "testdata/empty", 0)
    91  	if _, ok := err.(*NoGoError); !ok {
    92  		t.Fatal(`Import("testdata/empty") did not return NoGoError.`)
    93  	}
    94  }
    95  
    96  func TestMultiplePackageImport(t *testing.T) {
    97  	_, err := Import(".", "testdata/multi", 0)
    98  	mpe, ok := err.(*MultiplePackageError)
    99  	if !ok {
   100  		t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`)
   101  	}
   102  	want := &MultiplePackageError{
   103  		Dir:      filepath.FromSlash("testdata/multi"),
   104  		Packages: []string{"main", "test_package"},
   105  		Files:    []string{"file.go", "file_appengine.go"},
   106  	}
   107  	if !reflect.DeepEqual(mpe, want) {
   108  		t.Errorf("got %#v; want %#v", mpe, want)
   109  	}
   110  }
   111  
   112  func TestLocalDirectory(t *testing.T) {
   113  	if runtime.GOOS == "darwin" {
   114  		switch runtime.GOARCH {
   115  		case "arm", "arm64":
   116  			t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
   117  		}
   118  	}
   119  
   120  	cwd, err := os.Getwd()
   121  	if err != nil {
   122  		t.Fatal(err)
   123  	}
   124  
   125  	p, err := ImportDir(cwd, 0)
   126  	if err != nil {
   127  		t.Fatal(err)
   128  	}
   129  	if p.ImportPath != "go/build" {
   130  		t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build")
   131  	}
   132  }
   133  
   134  func TestShouldBuild(t *testing.T) {
   135  	const file1 = "// +build tag1\n\n" +
   136  		"package main\n"
   137  	want1 := map[string]bool{"tag1": true}
   138  
   139  	const file2 = "// +build cgo\n\n" +
   140  		"// This package implements parsing of tags like\n" +
   141  		"// +build tag1\n" +
   142  		"package build"
   143  	want2 := map[string]bool{"cgo": true}
   144  
   145  	const file3 = "// Copyright The Go Authors.\n\n" +
   146  		"package build\n\n" +
   147  		"// shouldBuild checks tags given by lines of the form\n" +
   148  		"// +build tag\n" +
   149  		"func shouldBuild(content []byte)\n"
   150  	want3 := map[string]bool{}
   151  
   152  	ctx := &Context{BuildTags: []string{"tag1"}}
   153  	m := map[string]bool{}
   154  	if !ctx.shouldBuild([]byte(file1), m, nil) {
   155  		t.Errorf("shouldBuild(file1) = false, want true")
   156  	}
   157  	if !reflect.DeepEqual(m, want1) {
   158  		t.Errorf("shouldBuild(file1) tags = %v, want %v", m, want1)
   159  	}
   160  
   161  	m = map[string]bool{}
   162  	if ctx.shouldBuild([]byte(file2), m, nil) {
   163  		t.Errorf("shouldBuild(file2) = true, want false")
   164  	}
   165  	if !reflect.DeepEqual(m, want2) {
   166  		t.Errorf("shouldBuild(file2) tags = %v, want %v", m, want2)
   167  	}
   168  
   169  	m = map[string]bool{}
   170  	ctx = &Context{BuildTags: nil}
   171  	if !ctx.shouldBuild([]byte(file3), m, nil) {
   172  		t.Errorf("shouldBuild(file3) = false, want true")
   173  	}
   174  	if !reflect.DeepEqual(m, want3) {
   175  		t.Errorf("shouldBuild(file3) tags = %v, want %v", m, want3)
   176  	}
   177  }
   178  
   179  type readNopCloser struct {
   180  	io.Reader
   181  }
   182  
   183  func (r readNopCloser) Close() error {
   184  	return nil
   185  }
   186  
   187  var (
   188  	ctxtP9      = Context{GOARCH: "arm", GOOS: "plan9"}
   189  	ctxtAndroid = Context{GOARCH: "arm", GOOS: "android"}
   190  )
   191  
   192  var matchFileTests = []struct {
   193  	ctxt  Context
   194  	name  string
   195  	data  string
   196  	match bool
   197  }{
   198  	{ctxtP9, "foo_arm.go", "", true},
   199  	{ctxtP9, "foo1_arm.go", "// +build linux\n\npackage main\n", false},
   200  	{ctxtP9, "foo_darwin.go", "", false},
   201  	{ctxtP9, "foo.go", "", true},
   202  	{ctxtP9, "foo1.go", "// +build linux\n\npackage main\n", false},
   203  	{ctxtP9, "foo.badsuffix", "", false},
   204  	{ctxtAndroid, "foo_linux.go", "", true},
   205  	{ctxtAndroid, "foo_android.go", "", true},
   206  	{ctxtAndroid, "foo_plan9.go", "", false},
   207  	{ctxtAndroid, "android.go", "", true},
   208  	{ctxtAndroid, "plan9.go", "", true},
   209  	{ctxtAndroid, "plan9_test.go", "", true},
   210  	{ctxtAndroid, "arm.s", "", true},
   211  	{ctxtAndroid, "amd64.s", "", true},
   212  }
   213  
   214  func TestMatchFile(t *testing.T) {
   215  	for _, tt := range matchFileTests {
   216  		ctxt := tt.ctxt
   217  		ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) {
   218  			if path != "x+"+tt.name {
   219  				t.Fatalf("OpenFile asked for %q, expected %q", path, "x+"+tt.name)
   220  			}
   221  			return &readNopCloser{strings.NewReader(tt.data)}, nil
   222  		}
   223  		ctxt.JoinPath = func(elem ...string) string {
   224  			return strings.Join(elem, "+")
   225  		}
   226  		match, err := ctxt.MatchFile("x", tt.name)
   227  		if match != tt.match || err != nil {
   228  			t.Fatalf("MatchFile(%q) = %v, %v, want %v, nil", tt.name, match, err, tt.match)
   229  		}
   230  	}
   231  }
   232  
   233  func TestImportCmd(t *testing.T) {
   234  	if runtime.GOOS == "darwin" {
   235  		switch runtime.GOARCH {
   236  		case "arm", "arm64":
   237  			t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
   238  		}
   239  	}
   240  
   241  	p, err := Import("cmd/internal/objfile", "", 0)
   242  	if err != nil {
   243  		t.Fatal(err)
   244  	}
   245  	if !strings.HasSuffix(filepath.ToSlash(p.Dir), "src/cmd/internal/objfile") {
   246  		t.Fatalf("Import cmd/internal/objfile returned Dir=%q, want %q", filepath.ToSlash(p.Dir), ".../src/cmd/internal/objfile")
   247  	}
   248  }
   249  
   250  var (
   251  	expandSrcDirPath = filepath.Join(string(filepath.Separator)+"projects", "src", "add")
   252  )
   253  
   254  var expandSrcDirTests = []struct {
   255  	input, expected string
   256  }{
   257  	{"-L ${SRCDIR}/libs -ladd", "-L /projects/src/add/libs -ladd"},
   258  	{"${SRCDIR}/add_linux_386.a -pthread -lstdc++", "/projects/src/add/add_linux_386.a -pthread -lstdc++"},
   259  	{"Nothing to expand here!", "Nothing to expand here!"},
   260  	{"$", "$"},
   261  	{"$$", "$$"},
   262  	{"${", "${"},
   263  	{"$}", "$}"},
   264  	{"$FOO ${BAR}", "$FOO ${BAR}"},
   265  	{"Find me the $SRCDIRECTORY.", "Find me the $SRCDIRECTORY."},
   266  	{"$SRCDIR is missing braces", "$SRCDIR is missing braces"},
   267  }
   268  
   269  func TestExpandSrcDir(t *testing.T) {
   270  	for _, test := range expandSrcDirTests {
   271  		output, _ := expandSrcDir(test.input, expandSrcDirPath)
   272  		if output != test.expected {
   273  			t.Errorf("%q expands to %q with SRCDIR=%q when %q is expected", test.input, output, expandSrcDirPath, test.expected)
   274  		} else {
   275  			t.Logf("%q expands to %q with SRCDIR=%q", test.input, output, expandSrcDirPath)
   276  		}
   277  	}
   278  }
   279  
   280  func TestShellSafety(t *testing.T) {
   281  	tests := []struct {
   282  		input, srcdir, expected string
   283  		result                  bool
   284  	}{
   285  		{"-I${SRCDIR}/../include", "/projects/src/issue 11868", "-I/projects/src/issue 11868/../include", true},
   286  		{"-I${SRCDIR}", "wtf$@%", "-Iwtf$@%", true},
   287  		{"-X${SRCDIR}/1,${SRCDIR}/2", "/projects/src/issue 11868", "-X/projects/src/issue 11868/1,/projects/src/issue 11868/2", true},
   288  		{"-I/tmp -I/tmp", "/tmp2", "-I/tmp -I/tmp", false},
   289  		{"-I/tmp", "/tmp/[0]", "-I/tmp", true},
   290  		{"-I${SRCDIR}/dir", "/tmp/[0]", "-I/tmp/[0]/dir", false},
   291  	}
   292  	for _, test := range tests {
   293  		output, ok := expandSrcDir(test.input, test.srcdir)
   294  		if ok != test.result {
   295  			t.Errorf("Expected %t while %q expands to %q with SRCDIR=%q; got %t", test.result, test.input, output, test.srcdir, ok)
   296  		}
   297  		if output != test.expected {
   298  			t.Errorf("Expected %q while %q expands with SRCDIR=%q; got %q", test.expected, test.input, test.srcdir, output)
   299  		}
   300  	}
   301  }
   302  
   303  // Want to get a "cannot find package" error when directory for package does not exist.
   304  func TestImportDirNotExist(t *testing.T) {
   305  	testenv.MustHaveGoBuild(t) // really must just have source
   306  	ctxt := Default
   307  	ctxt.GOPATH = ""
   308  
   309  	tests := []struct {
   310  		label        string
   311  		path, srcDir string
   312  		mode         ImportMode
   313  	}{
   314  		{"Import(full, 0)", "go/build/doesnotexist", "", 0},
   315  		{"Import(local, 0)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), 0},
   316  		{"Import(full, FindOnly)", "go/build/doesnotexist", "", FindOnly},
   317  		{"Import(local, FindOnly)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), FindOnly},
   318  	}
   319  	for _, test := range tests {
   320  		_, err := ctxt.Import(test.path, test.srcDir, test.mode)
   321  		if err == nil || !strings.HasPrefix(err.Error(), "cannot find package") {
   322  			t.Errorf(`%s got error: %q, want "cannot find package" error`, test.label, err)
   323  		}
   324  	}
   325  }
   326  
   327  func TestImportVendor(t *testing.T) {
   328  	testenv.MustHaveGoBuild(t) // really must just have source
   329  	ctxt := Default
   330  	ctxt.GOPATH = ""
   331  	p, err := ctxt.Import("golang_org/x/net/http2/hpack", filepath.Join(ctxt.GOROOT, "src/net/http"), 0)
   332  	if err != nil {
   333  		t.Fatalf("cannot find vendored golang_org/x/net/http2/hpack from net/http directory: %v", err)
   334  	}
   335  	want := "vendor/golang_org/x/net/http2/hpack"
   336  	if p.ImportPath != want {
   337  		t.Fatalf("Import succeeded but found %q, want %q", p.ImportPath, want)
   338  	}
   339  }
   340  
   341  func TestImportVendorFailure(t *testing.T) {
   342  	testenv.MustHaveGoBuild(t) // really must just have source
   343  	ctxt := Default
   344  	ctxt.GOPATH = ""
   345  	p, err := ctxt.Import("x.com/y/z", filepath.Join(ctxt.GOROOT, "src/net/http"), 0)
   346  	if err == nil {
   347  		t.Fatalf("found made-up package x.com/y/z in %s", p.Dir)
   348  	}
   349  
   350  	e := err.Error()
   351  	if !strings.Contains(e, " (vendor tree)") {
   352  		t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
   353  	}
   354  }
   355  
   356  func TestImportVendorParentFailure(t *testing.T) {
   357  	testenv.MustHaveGoBuild(t) // really must just have source
   358  	ctxt := Default
   359  	ctxt.GOPATH = ""
   360  	// This import should fail because the vendor/golang.org/x/net/http2 directory has no source code.
   361  	p, err := ctxt.Import("golang_org/x/net/http2", filepath.Join(ctxt.GOROOT, "src/net/http"), 0)
   362  	if err == nil {
   363  		t.Fatalf("found empty parent in %s", p.Dir)
   364  	}
   365  	if p != nil && p.Dir != "" {
   366  		t.Fatalf("decided to use %s", p.Dir)
   367  	}
   368  	e := err.Error()
   369  	if !strings.Contains(e, " (vendor tree)") {
   370  		t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
   371  	}
   372  }