-
-
Notifications
You must be signed in to change notification settings - Fork 435
/
Copy pathoptimizer_test.go
116 lines (90 loc) · 2.47 KB
/
optimizer_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
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
package optimizer_test
import (
"strings"
"testing"
"github.com/antonmedv/expr/ast"
"github.com/antonmedv/expr/checker"
"github.com/antonmedv/expr/conf"
"github.com/antonmedv/expr/optimizer"
"github.com/antonmedv/expr/parser"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestOptimize_constant_folding(t *testing.T) {
tree, err := parser.Parse(`[1,2,3][5*5-25]`)
require.NoError(t, err)
err = optimizer.Optimize(&tree.Node, nil)
require.NoError(t, err)
expected := &ast.MemberNode{
Node: &ast.ConstantNode{Value: []interface{}{1, 2, 3}},
Property: &ast.IntegerNode{Value: 0},
}
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}
func TestOptimize_in_array(t *testing.T) {
config := conf.New(map[string]int{"v": 0})
tree, err := parser.Parse(`v in [1,2,3]`)
require.NoError(t, err)
_, err = checker.Check(tree, config)
require.NoError(t, err)
err = optimizer.Optimize(&tree.Node, nil)
require.NoError(t, err)
expected := &ast.BinaryNode{
Operator: "in",
Left: &ast.IdentifierNode{Value: "v"},
Right: &ast.ConstantNode{Value: map[int]struct{}{1: {}, 2: {}, 3: {}}},
}
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}
func TestOptimize_in_range(t *testing.T) {
tree, err := parser.Parse(`age in 18..31`)
require.NoError(t, err)
err = optimizer.Optimize(&tree.Node, nil)
require.NoError(t, err)
left := &ast.IdentifierNode{
Value: "age",
}
expected := &ast.BinaryNode{
Operator: "and",
Left: &ast.BinaryNode{
Operator: ">=",
Left: left,
Right: &ast.IntegerNode{
Value: 18,
},
},
Right: &ast.BinaryNode{
Operator: "<=",
Left: left,
Right: &ast.IntegerNode{
Value: 31,
},
},
}
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}
func TestOptimize_const_range(t *testing.T) {
tree, err := parser.Parse(`-1..1`)
require.NoError(t, err)
err = optimizer.Optimize(&tree.Node, nil)
require.NoError(t, err)
expected := &ast.ConstantNode{
Value: []int{-1, 0, 1},
}
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}
func TestOptimize_const_expr(t *testing.T) {
tree, err := parser.Parse(`upper("hello")`)
require.NoError(t, err)
env := map[string]interface{}{
"upper": strings.ToUpper,
}
config := conf.New(env)
config.ConstExpr("upper")
err = optimizer.Optimize(&tree.Node, config)
require.NoError(t, err)
expected := &ast.ConstantNode{
Value: "HELLO",
}
assert.Equal(t, ast.Dump(expected), ast.Dump(tree.Node))
}