-
Notifications
You must be signed in to change notification settings - Fork 0
/
inspect_test.go
79 lines (64 loc) · 1.76 KB
/
inspect_test.go
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
package astor
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
)
const parserFlags = parser.ParseComments | parser.AllErrors
func runInspector(t *testing.T, infile, outfile string, visitor Visitor) {
var err error
var inputSrc []byte
var expectedOut []byte
inputSrc, err = ioutil.ReadFile(infile)
assert.NoError(t, err, "Error reading input")
expectedOut, err = ioutil.ReadFile(outfile)
assert.NoError(t, err, "Error reading expected output")
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, infile, inputSrc, parserFlags)
assert.NoError(t, err, "Error parsing input")
inspector := NewInspector(visitor)
result := inspector.Inspect(f)
actualOutBuf := new(bytes.Buffer)
err = format.Node(actualOutBuf, fset, result)
assert.NoError(t, err, "Error formatting output AST")
assert.Equal(t, string(expectedOut), actualOutBuf.String(), "Expected output doesn't match actual output")
}
func TestPrependingFuncName(t *testing.T) {
visitor := func(i Inspector, n ast.Node) bool {
if n, ok := n.(*ast.FuncDecl); ok {
n.Name = ast.NewIdent(fmt.Sprintf("Foo%s", n.Name.String()))
i.Replace(n)
return false
}
return true
}
runInspector(
t,
"test-samples/prepending-func-name.go.in",
"test-samples/prepending-func-name.go.out",
visitor)
}
func TestChangePointerToInterface(t *testing.T) {
visitor := func(i Inspector, n ast.Node) bool {
if _, ok := n.(*ast.StarExpr); ok {
newNode := &ast.SelectorExpr{
X: ast.NewIdent("pkg"),
Sel: ast.NewIdent("InterfaceName"),
}
i.Replace(newNode)
return false
}
return true
}
runInspector(
t,
"test-samples/pointer-to-interface.go.in",
"test-samples/pointer-to-interface.go.out",
visitor)
}