1
2
3
4
5 package buildutil_test
6
7 import (
8 "go/build"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strings"
13 "testing"
14
15 "golang.org/x/tools/go/buildutil"
16 "golang.org/x/tools/go/packages/packagestest"
17 )
18
19 func TestContainingPackage(t *testing.T) {
20 if runtime.Compiler == "gccgo" {
21 t.Skip("gccgo has no GOROOT")
22 }
23
24 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{
25 {Name: "golang.org/x/tools/go/buildutil", Files: packagestest.MustCopyFileTree(".")}})
26 defer exported.Cleanup()
27
28 goroot := runtime.GOROOT()
29 var gopath string
30 for _, env := range exported.Config.Env {
31 if !strings.HasPrefix(env, "GOPATH=") {
32 continue
33 }
34 gopath = strings.TrimPrefix(env, "GOPATH=")
35 }
36 if gopath == "" {
37 t.Fatal("Failed to fish GOPATH out of env: ", exported.Config.Env)
38 }
39 buildutildir := filepath.Join(gopath, "golang.org", "x", "tools", "go", "buildutil")
40
41 type Test struct {
42 gopath, filename, wantPkg string
43 }
44
45 tests := []Test{
46 {gopath, goroot + "/src/fmt/print.go", "fmt"},
47 {gopath, goroot + "/src/encoding/json/foo.go", "encoding/json"},
48 {gopath, goroot + "/src/encoding/missing/foo.go", "(not found)"},
49 {gopath, gopath + "/src/golang.org/x/tools/go/buildutil/util_test.go",
50 "golang.org/x/tools/go/buildutil"},
51 }
52
53 if runtime.GOOS != "windows" && runtime.GOOS != "plan9" {
54
55 tmp, err := os.MkdirTemp(os.TempDir(), "go")
56 if err != nil {
57 t.Errorf("Unable to create a temporary directory in %s", os.TempDir())
58 }
59
60 defer os.RemoveAll(tmp)
61
62
63
64 if err := os.Symlink(gopath+"/src", tmp+"/src"); err != nil {
65 t.Fatal(err)
66 }
67 tests = append(tests, []Test{
68 {gopath, tmp + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
69 {tmp, gopath + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
70 {tmp, tmp + "/src/golang.org/x/tools/go/buildutil/util_test.go", "golang.org/x/tools/go/buildutil"},
71 }...)
72 }
73
74 for _, test := range tests {
75 var got string
76 var buildContext = build.Default
77 buildContext.GOPATH = test.gopath
78 bp, err := buildutil.ContainingPackage(&buildContext, buildutildir, test.filename)
79 if err != nil {
80 got = "(not found)"
81 } else {
82 got = bp.ImportPath
83 }
84 if got != test.wantPkg {
85 t.Errorf("ContainingPackage(%q) = %s, want %s", test.filename, got, test.wantPkg)
86 }
87 }
88
89 }
90
View as plain text