sq/libsq/ast/walker_test.go

54 lines
1.1 KiB
Go
Raw Normal View History

2016-10-17 07:14:01 +03:00
package ast
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/neilotoole/slogt"
2016-10-17 07:14:01 +03:00
)
func TestWalker(t *testing.T) {
const q1 = `@mydb1 | .user | join(.address, .user.uid == .address.uid) | .uid, .username, .country`
2016-10-17 07:14:01 +03:00
p := getSLQParser(q1)
2016-10-17 07:14:01 +03:00
query := p.Query()
ast, err := buildAST(slogt.New(t), query)
2016-10-17 07:14:01 +03:00
assert.Nil(t, err)
assert.NotNil(t, ast)
walker := NewWalker(ast)
2016-10-17 07:14:01 +03:00
count := 0
visitor := func(w *Walker, node Node) error {
2016-10-17 07:14:01 +03:00
count++
return w.visitChildren(node)
}
walker.AddVisitor(typeJoinNode, visitor)
2016-10-17 07:14:01 +03:00
err = walker.Walk()
assert.Nil(t, err)
assert.Equal(t, 1, count)
// test multiple visitors on the same node type
walker = NewWalker(ast)
2016-10-17 07:14:01 +03:00
countA := 0
visitorA := func(w *Walker, node Node) error {
2016-10-17 07:14:01 +03:00
countA++
return w.visitChildren(node)
}
countB := 0
visitorB := func(w *Walker, node Node) error {
2016-10-17 07:14:01 +03:00
countB++
return w.visitChildren(node)
}
walker.AddVisitor(typeTblSelectorNode, visitorA)
walker.AddVisitor(typeColSelectorNode, visitorB)
2016-10-17 07:14:01 +03:00
err = walker.Walk()
assert.Nil(t, err)
assert.Equal(t, 1, countA)
assert.Equal(t, 3, countB)
2016-10-17 07:14:01 +03:00
}