github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/codegen/loaderx/types_test.go (about) 1 package loaderx 2 3 import ( 4 "go/types" 5 "strconv" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestForEachFuncResult(t *testing.T) { 12 tt := assert.New(t) 13 14 pkgImportPath, program := NewTestProgram(` 15 package main 16 17 type String string 18 19 func fnA () String { 20 return "" 21 } 22 23 func fn () (a interface{}, b String) { 24 { 25 a = nil 26 } 27 switch (a) { 28 case "a3": 29 a = "a3" 30 b = "b3" 31 return 32 } 33 if true { 34 a = "a0" 35 return fnA(), "b1" 36 } 37 b = "b2" 38 return 39 } 40 41 func fn2 () (a interface{}, b String) { 42 a, b = fn() 43 return 44 } 45 46 func Fn () (a interface{}, b String) { 47 return fn2() 48 } 49 `) 50 51 q := NewQuery(program, pkgImportPath) 52 typeFunc := q.Func("Fn") 53 54 rets := [][]string{} 55 ForEachFuncResult(program, typeFunc, func(resultTypeAndValues ...types.TypeAndValue) { 56 ret := make([]string, len(resultTypeAndValues)) 57 for i, r := range resultTypeAndValues { 58 if r.IsValue() { 59 ret[i], _ = strconv.Unquote(r.Value.String()) 60 } else { 61 ret[i] = r.Type.String() 62 } 63 } 64 rets = append(rets, ret) 65 }) 66 67 tt.Equal([][]string{ 68 {"a3", "b3"}, 69 {pkgImportPath + ".String", "b1"}, 70 {"untyped nil", "b2"}, 71 }, rets) 72 } 73 74 func TestMethodOf(t *testing.T) { 75 tt := assert.New(t) 76 77 pkgImportPath, program := NewTestProgram(` 78 package main 79 80 type SomeType struct { 81 F string 82 } 83 84 func (a SomeType) Fn() {} 85 86 type SomeTypeAlias = SomeType 87 88 type SomeTypeCompose struct { 89 SomeType 90 } 91 92 type SomeTypeReDef SomeType 93 94 95 type SomeTypeDeepCompose struct { 96 SomeTypeCompose 97 } 98 `) 99 100 q := NewQuery(program, pkgImportPath) 101 102 { 103 typeName := q.TypeName("SomeType") 104 typeFunc := MethodOf(typeName.Type().(*types.Named), "Fn") 105 tt.NotNil(typeFunc) 106 } 107 108 { 109 typeName := q.TypeName("SomeTypeAlias") 110 typeFunc := MethodOf(typeName.Type().(*types.Named), "Fn") 111 tt.NotNil(typeFunc) 112 } 113 114 { 115 typeName := q.TypeName("SomeTypeCompose") 116 typeFunc := MethodOf(typeName.Type().(*types.Named), "Fn") 117 tt.NotNil(typeFunc) 118 } 119 120 { 121 typeName := q.TypeName("SomeTypeDeepCompose") 122 typeFunc := MethodOf(typeName.Type().(*types.Named), "Fn") 123 tt.NotNil(typeFunc) 124 } 125 126 { 127 typeName := q.TypeName("SomeTypeReDef") 128 typeFunc := MethodOf(typeName.Type().(*types.Named), "Fn") 129 tt.Nil(typeFunc) 130 } 131 }