github.com/shranet/mobile@v0.0.0-20200814083559-5702cdcd481b/internal/importers/ast_test.go (about)

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