1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
package convert
import (
"go/ast"
)
/*
* Rewrites any other top level funcs that receive a *testing.T param
*/
func rewriteOtherFuncsToUseGinkgoT(declarations []ast.Decl) {
for _, decl := range declarations {
decl, ok := decl.(*ast.FuncDecl)
if !ok {
continue
}
for _, param := range decl.Type.Params.List {
starExpr, ok := param.Type.(*ast.StarExpr)
if !ok {
continue
}
selectorExpr, ok := starExpr.X.(*ast.SelectorExpr)
if !ok {
continue
}
xIdent, ok := selectorExpr.X.(*ast.Ident)
if !ok || xIdent.Name != "testing" {
continue
}
if selectorExpr.Sel.Name != "T" {
continue
}
param.Type = newGinkgoTInterface()
}
}
}
/*
* Walks all of the nodes in the file, replacing *testing.T in struct
* and func literal nodes. eg:
* type foo struct { *testing.T }
* var bar = func(t *testing.T) { }
*/
func walkNodesInRootNodeReplacingTestingT(rootNode *ast.File) {
ast.Inspect(rootNode, func(node ast.Node) bool {
if node == nil {
return false
}
switch node := node.(type) {
case *ast.StructType:
replaceTestingTsInStructType(node)
case *ast.FuncLit:
replaceTypeDeclTestingTsInFuncLiteral(node)
}
return true
})
}
/*
* replaces named *testing.T inside a composite literal
*/
func replaceNamedTestingTsInKeyValueExpression(kve *ast.KeyValueExpr, testingT string) {
ident, ok := kve.Value.(*ast.Ident)
if !ok {
return
}
if ident.Name == testingT {
kve.Value = newGinkgoTFromIdent(ident)
}
}
/*
* replaces *testing.T params in a func literal with GinkgoT
*/
func replaceTypeDeclTestingTsInFuncLiteral(functionLiteral *ast.FuncLit) {
for _, arg := range functionLiteral.Type.Params.List {
starExpr, ok := arg.Type.(*ast.StarExpr)
if !ok {
continue
}
selectorExpr, ok := starExpr.X.(*ast.SelectorExpr)
if !ok {
continue
}
target, ok := selectorExpr.X.(*ast.Ident)
if !ok {
continue
}
if target.Name == "testing" && selectorExpr.Sel.Name == "T" {
arg.Type = newGinkgoTInterface()
}
}
}
/*
* Replaces *testing.T types inside of a struct declaration with a GinkgoT
* eg: type foo struct { *testing.T }
*/
func replaceTestingTsInStructType(structType *ast.StructType) {
for _, field := range structType.Fields.List {
starExpr, ok := field.Type.(*ast.StarExpr)
if !ok {
continue
}
selectorExpr, ok := starExpr.X.(*ast.SelectorExpr)
if !ok {
continue
}
xIdent, ok := selectorExpr.X.(*ast.Ident)
if !ok {
continue
}
if xIdent.Name == "testing" && selectorExpr.Sel.Name == "T" {
field.Type = newGinkgoTInterface()
}
}
}
|