1 // Copyright 2014 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.
16 "golang.org/x/tools/go/buildutil"
17 "golang.org/x/tools/go/packages/packagestest"
20 func TestContainingPackage(t *testing.T) {
21 if runtime.Compiler == "gccgo" {
22 t.Skip("gccgo has no GOROOT")
25 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{
26 {Name: "golang.org/x/tools/go/buildutil", Files: packagestest.MustCopyFileTree(".")}})
27 defer exported.Cleanup()
29 goroot := runtime.GOROOT()
31 for _, env := range exported.Config.Env {
32 if !strings.HasPrefix(env, "GOPATH=") {
35 gopath = strings.TrimPrefix(env, "GOPATH=")
38 t.Fatal("Failed to fish GOPATH out of env: ", exported.Config.Env)
40 buildutildir := filepath.Join(gopath, "golang.org", "x", "tools", "go", "buildutil")
43 gopath, filename, wantPkg string
47 {gopath, goroot + "/src/fmt/print.go", "fmt"},
48 {gopath, goroot + "/src/encoding/json/foo.go", "encoding/json"},
49 {gopath, goroot + "/src/encoding/missing/foo.go", "(not found)"},
50 {gopath, gopath + "/src/golang.org/x/tools/go/buildutil/util_test.go",
51 "golang.org/x/tools/go/buildutil"},
54 if runtime.GOOS != "windows" && runtime.GOOS != "plan9" {
55 // Make a symlink to gopath for test
56 tmp, err := ioutil.TempDir(os.TempDir(), "go")
58 t.Errorf("Unable to create a temporary directory in %s", os.TempDir())
61 defer os.RemoveAll(tmp)
63 // symlink between $GOPATH/src and /tmp/go/src
64 // in order to test all possible symlink cases
65 if err := os.Symlink(gopath+"/src", tmp+"/src"); err != nil {
68 tests = append(tests, []Test{
69 {gopath, tmp + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
70 {tmp, gopath + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
71 {tmp, tmp + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
75 for _, test := range tests {
77 var buildContext = build.Default
78 buildContext.GOPATH = test.gopath
79 bp, err := buildutil.ContainingPackage(&buildContext, buildutildir, test.filename)
85 if got != test.wantPkg {
86 t.Errorf("ContainingPackage(%q) = %s, want %s", test.filename, got, test.wantPkg)