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