-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer_test.go
63 lines (60 loc) · 1.93 KB
/
tokenizer_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
package koalaburrito
import (
"testing"
)
func TestTokenization(t *testing.T) {
tokenizer := MakeTokenizer()
tokenizer.AddPattern(`([-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+|[0-9]+))`, "NUMBER")
tokenizer.AddPattern(`\+`, "ADD")
tokenizer.AddPattern(`-`, "SUBTRACT")
tokenizer.AddPattern(`/`, "DIVIDE")
tokenizer.AddPattern(`\*`, "MULTIPLY")
tokenizer.AddPattern(`\s+`, "WHITESPACE")
c := make(chan TokenOrError)
go tokenizer.Match("5.5 2 1 1 +1 -1.1 +/-*", c)
runOne := func(tokenType, tokenString string) {
tok := <-c
if tok.Type() != tokenType {
t.Errorf("Token type did not match: expected %v but got %#v", tokenType, tok)
}
if tok.String() != tokenString {
t.Errorf("Token string did not match: expected %v but got %#v", tokenString, tok)
}
}
runOne("NUMBER", "5.5")
runOne("WHITESPACE", " ")
runOne("NUMBER", "2")
runOne("WHITESPACE", " ")
runOne("NUMBER", "1")
runOne("WHITESPACE", " ")
runOne("NUMBER", "1")
runOne("WHITESPACE", " ")
runOne("NUMBER", "+1")
runOne("WHITESPACE", " ")
runOne("NUMBER", "-1.1")
runOne("WHITESPACE", " ")
runOne("ADD", "+")
runOne("DIVIDE", "/")
runOne("SUBTRACT", "-")
runOne("MULTIPLY", "*")
}
func TestTokenizationError(t *testing.T) {
tokenizer := MakeTokenizer()
tokenizer.AddPattern(`\s+`, "WHITESPACE")
c := make(chan TokenOrError)
go tokenizer.Match(" 5", c)
runOne := func(tokenType, tokenString string, position int) {
tok := <-c
if tok.Type() != tokenType {
t.Errorf("Token type did not match: expected %v but got %#v", tokenType, tok)
}
if tok.String() != tokenString {
t.Errorf("Token string did not match: expected %v but got %#v", tokenString, tok)
}
if tok.Position() != position {
t.Errorf("Token position was expected to be %v but instead it was %v", position, tok.Position())
}
}
runOne("WHITESPACE", " ", 1)
runOne("ERROR", "Error at position 5", 5)
}