-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwalker_test.go
57 lines (47 loc) · 1.5 KB
/
walker_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
package walker
import (
"github.com/robertkrimen/otto/ast"
"github.com/robertkrimen/otto/parser"
"reflect"
"testing"
)
type testVisitor struct {
VisitorImpl
ancestors []Metadata
}
func (v *testVisitor) VisitIdentifier(w *Walker, node *ast.Identifier, metadata []Metadata) Metadata {
v.ancestors = metadata
return CurrentMetadata(metadata)
}
func TestWalker(t *testing.T) {
tests := []struct {
src string
size int
parent reflect.Type
}{
{`1 + b`, 5, reflect.TypeOf((*ast.BinaryExpression)(nil))},
{`c++`, 5, reflect.TypeOf((*ast.UnaryExpression)(nil))},
{`function fun(){}`, 5, reflect.TypeOf((*ast.FunctionLiteral)(nil))},
{`while(i){}`, 4, reflect.TypeOf((*ast.WhileStatement)(nil))},
{`if(i){}`, 4, reflect.TypeOf((*ast.IfStatement)(nil))},
{`with(i){}`, 4, reflect.TypeOf((*ast.WithStatement)(nil))},
{`switch(i){}`, 4, reflect.TypeOf((*ast.SwitchStatement)(nil))},
}
for i, test := range tests {
program, err := parser.ParseFile(nil, "", test.src, 0)
if err != nil {
t.Errorf("[%v] Failed, %v", i, err)
}
visitor := &testVisitor{}
walker := NewWalker(visitor)
walker.Begin(program)
if test.size != len(visitor.ancestors) {
t.Errorf("[%v] Failed, number of ancestors not correct, %v != %v", i, test.size, len(visitor.ancestors))
}
parent := visitor.ancestors[len(visitor.ancestors)-2].Node()
typeOfParent := reflect.TypeOf(parent)
if test.parent != typeOfParent {
t.Errorf("[%v] Failed, parent not correct, %v != %v", i, test.parent, typeOfParent)
}
}
}