| 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. |
| 4 | |
| 5 | package typeutil_test |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | "go/ast" |
| 10 | "go/parser" |
| 11 | "go/token" |
| 12 | "go/types" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "golang.org/x/tools/go/types/typeutil" |
| 17 | ) |
| 18 | |
| 19 | type closure map[string]*types.Package |
| 20 | |
| 21 | func (c closure) Import(path string) (*types.Package, error) { return c[path], nil } |
| 22 | |
| 23 | func TestDependencies(t *testing.T) { |
| 24 | packages := make(map[string]*types.Package) |
| 25 | conf := types.Config{ |
| 26 | Importer: closure(packages), |
| 27 | } |
| 28 | fset := token.NewFileSet() |
| 29 | |
| 30 | // All edges go to the right. |
| 31 | // /--D--B--A |
| 32 | // F \_C_/ |
| 33 | // \__E_/ |
| 34 | for i, content := range []string{ |
| 35 | `package a`, |
| 36 | `package c; import (_ "a")`, |
| 37 | `package b; import (_ "a")`, |
| 38 | `package e; import (_ "c")`, |
| 39 | `package d; import (_ "b"; _ "c")`, |
| 40 | `package f; import (_ "d"; _ "e")`, |
| 41 | } { |
| 42 | f, err := parser.ParseFile(fset, fmt.Sprintf("%d.go", i), content, 0) |
| 43 | if err != nil { |
| 44 | t.Fatal(err) |
| 45 | } |
| 46 | pkg, err := conf.Check(f.Name.Name, fset, []*ast.File{f}, nil) |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | packages[pkg.Path()] = pkg |
| 51 | } |
| 52 | |
| 53 | for _, test := range []struct { |
| 54 | roots, want string |
| 55 | }{ |
| 56 | {"a", "a"}, |
| 57 | {"b", "ab"}, |
| 58 | {"c", "ac"}, |
| 59 | {"d", "abcd"}, |
| 60 | {"e", "ace"}, |
| 61 | {"f", "abcdef"}, |
| 62 | |
| 63 | {"be", "abce"}, |
| 64 | {"eb", "aceb"}, |
| 65 | {"de", "abcde"}, |
| 66 | {"ed", "acebd"}, |
| 67 | {"ef", "acebdf"}, |
| 68 | } { |
| 69 | var pkgs []*types.Package |
| 70 | for _, r := range test.roots { |
| 71 | pkgs = append(pkgs, packages[string(r)]) |
| 72 | } |
| 73 | var got strings.Builder |
| 74 | for _, p := range typeutil.Dependencies(pkgs...) { |
| 75 | got.WriteString(p.Path()) |
| 76 | } |
| 77 | if got.String() != test.want { |
| 78 | t.Errorf("Dependencies(%q) = %q, want %q", test.roots, got.String(), test.want) |
| 79 | } |
| 80 | } |
| 81 | } |