-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer_test.go
119 lines (113 loc) · 2.73 KB
/
lexer_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
117
118
119
package calcu
import (
"reflect"
"strconv"
"testing"
"github.com/shopspring/decimal"
)
func TestMeasureValueFromString(t *testing.T) {
cases := []struct {
s string
expected func() MeasureValue
}{
{"1(10^3m3)", func() MeasureValue {
return MeasureValue{value: decimal.NewFromInt(1), unit: "10^3m3"}
}},
{"1kg/m3", func() MeasureValue {
return MeasureValue{value: decimal.NewFromInt(1), unit: "kg/m3"}
}},
{"1kg", func() MeasureValue {
return MeasureValue{value: decimal.NewFromInt(1), unit: "kg"}
}},
{"1.1E-04(Gg/10^3m3)", func() MeasureValue {
d, err := decimal.NewFromString("1.1E-04")
if err != nil {
panic(err)
}
return MeasureValue{value: d, unit: "Gg/10^3m3"}
}},
{"1.1E-04Gg/10^3m3", func() MeasureValue {
d, err := decimal.NewFromString("1.1E-04")
if err != nil {
panic(err)
}
return MeasureValue{value: d, unit: "Gg/10^3m3"}
}},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
mv, err := NewMeasureValueFromString(c.s)
if err != nil {
t.Fatal(err)
}
expected := c.expected()
if !mv.value.Equal(expected.value) {
t.Fatalf("expectd decimal value: %v, got: %v", expected.value, mv.value)
}
if mv.unit != expected.unit {
t.Fatalf("expectd unit: %v, got: %v", expected.unit, mv.unit)
}
})
}
}
func TestLexer(t *testing.T) {
cases := []struct {
expr string
expected []int
}{
{expr: `1kg/m3, 1kg`, expected: []int{NUM, UNIT, NUM, UNIT}},
{
expr: `SI = Convert(activity_value, activity_unit, "10^3m3", "hello", 123.123, "10(10^3m3)")`,
expected: []int{IDENT, IDENT, IDENT, IDENT, UNIT, LITERALSTR, NUM, LITERALMV},
},
{
expr: `fTypes("hello world", a, 1kg, "1kg", "10(10^3m3)");`,
expected: []int{IDENT, LITERALSTR, IDENT, NUM, UNIT, LITERALMV, LITERALMV},
},
{
expr: `m = 1;`,
expected: []int{IDENT, NUM},
},
{
expr: `me = 1;`,
expected: []int{IDENT, NUM},
},
{
expr: `me = 1m + 2m;`,
expected: []int{IDENT, NUM, UNIT, NUM, UNIT},
},
{
expr: `me = -1m;`,
expected: []int{IDENT, NUM, UNIT},
},
{
expr: `a *b * 44/12;`,
expected: []int{IDENT, IDENT, NUM, NUM},
},
{
expr: `a * b * (1 + 2);`,
expected: []int{IDENT, IDENT, NUM, NUM},
},
}
for i, c := range cases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
l := newLexer(c.expr)
var lvals []*exprSymType
var tokens []int
for {
var lval exprSymType
ret := l.Lex(&lval)
if ret == eof {
break
}
if lval.token != invalid {
tokens = append(tokens, lval.token)
}
}
_ = lvals
if !reflect.DeepEqual(c.expected, tokens) {
t.Fatalf("%d: %q: expected %d, but found %d", i, c.expr, c.expected, tokens)
}
})
}
}