| 1 | // Copyright 2016 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 importers |
| 6 | |
| 7 | import ( |
| 8 | "go/parser" |
| 9 | "go/token" |
| 10 | "reflect" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | func TestAnalyzer(t *testing.T) { |
| 15 | file := `package ast_test |
| 16 | |
| 17 | import "Prefix/some/pkg/Name" |
| 18 | import "Prefix/some/pkg/Name2" |
| 19 | |
| 20 | const c = Name.Constant |
| 21 | |
| 22 | type T struct { |
| 23 | Name.Type |
| 24 | unexported Name.Type2 |
| 25 | } |
| 26 | |
| 27 | func f() { |
| 28 | Name2.Func().Func().Func() |
| 29 | } |
| 30 | ` |
| 31 | fset := token.NewFileSet() |
| 32 | f, err := parser.ParseFile(fset, "ast_test.go", file, parser.AllErrors) |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | refs, err := AnalyzeFile(f, "Prefix/") |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | exps := []PkgRef{ |
| 41 | {Pkg: "some/pkg/Name", Name: "Constant"}, |
| 42 | {Pkg: "some/pkg/Name", Name: "Type"}, |
| 43 | {Pkg: "some/pkg/Name2", Name: "Func"}, |
| 44 | {Pkg: "some/pkg/Name", Name: "Type2"}, |
| 45 | } |
| 46 | if len(refs.Refs) != len(exps) { |
| 47 | t.Fatalf("expected %d references; got %d", len(exps), len(refs.Refs)) |
| 48 | } |
| 49 | for i, exp := range exps { |
| 50 | if got := refs.Refs[i]; exp != got { |
| 51 | t.Errorf("expected ref %v; got %v", exp, got) |
| 52 | } |
| 53 | } |
| 54 | if _, exists := refs.Names["Constant"]; !exists { |
| 55 | t.Errorf("expected \"Constant\" in the names set") |
| 56 | } |
| 57 | if len(refs.Embedders) != 1 { |
| 58 | t.Fatalf("expected 1 struct; got %d", len(refs.Embedders)) |
| 59 | } |
| 60 | s := refs.Embedders[0] |
| 61 | exp := Struct{ |
| 62 | Name: "T", |
| 63 | Pkg: "ast_test", |
| 64 | Refs: []PkgRef{{Pkg: "some/pkg/Name", Name: "Type"}}, |
| 65 | } |
| 66 | if !reflect.DeepEqual(exp, s) { |
| 67 | t.Errorf("expected struct %v; got %v", exp, s) |
| 68 | } |
| 69 | } |