-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy patheval_test.go
84 lines (73 loc) · 1.75 KB
/
eval_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
package goexpression
import (
"testing"
)
type mathTestValue struct {
input string
haserror bool
result float64
}
func TestMathEval(t *testing.T) {
var (
x float64 = 5
y float64 = 23
z float64 = 12.25
)
context := map[string]interface{}{
"x": x,
"y": y,
"z": z,
}
var tests []mathTestValue = []mathTestValue{
//Test Basic Calculations
{"2^2", false, 4},
{"1+1", false, 2},
{"-1+2", false, 1},
{"2-1", false, 1},
{"1-10", false, -9},
{"1+2*3", false, 7},
{"2*3+1", false, 7},
{"2*3/2", false, 2 * 3 / 2},
{"2/2*3", false, 2 / 2 * 3},
//Testing precedence
{"1+2*3/2", false, 1 + 2*3/2},
{"-3+1.5*2+5-2*2", false, -3 + 1.5*2 + 5 - 2*2},
{"4+3-2+1", false, 4 + 3 - 2 + 1},
{"2-3+4-2", false, 2 - 3 + 4 - 2},
{"2.4*3+1.5*2-3.1*4-1+2", false, 2.4*3 + 1.5*2 - 3.1*4 - 1 + 2},
//Testing brackets
{"(1+2)*3", false, (1 + 2) * 3},
{"3*(1+2)", false, 3 * (1 + 2)},
{"3*(1+2)*4", false, 3 * (1 + 2) * 4},
//Testing expressions with variables. Where {x:5}
{"2*x", false, 2 * x},
{"2*x+y+(z+x)*4", false, float64(2*x + y + (z+x)*4)},
{"1+x*(50-y)/z", false, float64(1 + x*(50-y)/z)},
}
for i, v := range tests {
ans := Eval(v.input, context)
//t.Log(i, ") ", v.input, "=", ans, " Expecting:", v.result)
if int(ans*1000) != int(v.result*1000) {
t.Error(i, ") ", v.input, "=", ans, " Expecting:", v.result)
}
}
}
type MyNumber struct {
Value float64
}
func (m MyNumber) Float64() float64 {
return m.Value
}
func TestEvalContextSetupWithFloater(t *testing.T) {
ctx := map[string]interface{}{
"x": MyNumber{Value: 5},
"y": MyNumber{Value: 6},
}
expected := 11.0
// Act
actual := Eval("x+y", ctx)
// Assert
if actual != expected {
t.Fatalf("invalid result! got=%v; want=%v", actual, expected)
}
}