-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_rule_parser.py
104 lines (93 loc) · 3.03 KB
/
test_rule_parser.py
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
import unittest
from rule_parser import Lexer, Parser, RuleParser
class TestLexer(unittest.TestCase):
def test_tokenize(self):
rule_dsl = 'IF age > 18 AND gender == "male" THEN is_eligible = true'
lexer = Lexer(rule_dsl)
lexer.tokenize()
expected_tokens = [
('IF', 'IF'),
('IDENTIFIER', 'age'),
('>', '>'),
('NUMBER', '18'),
('AND', 'AND'),
('IDENTIFIER', 'gender'),
('==', '=='),
('STRING', '"male"'),
('THEN', 'THEN'),
('IDENTIFIER', 'is_eligible'),
('=', '='),
('IDENTIFIER', 'true')
]
self.assertEqual(lexer.tokens, expected_tokens)
class TestParser(unittest.TestCase):
def test_parse_expression(self):
tokens = [
('IDENTIFIER', 'age'),
('>', '>'),
('NUMBER', '18'),
('AND', 'AND'),
('IDENTIFIER', 'gender'),
('==', '=='),
('STRING', '"male"')
]
parser = Parser(tokens)
ast = parser.parse_expression()
expected_ast = (
'AND',
('>', ('IDENTIFIER', 'age'), ('NUMBER', 18)),
('==', ('IDENTIFIER', 'gender'), ('STRING', 'male'))
)
self.assertEqual(ast, expected_ast)
def test_parse_term(self):
tokens = [
('IDENTIFIER', 'age'),
('>', '>'),
('NUMBER', '18')
]
parser = Parser(tokens)
ast = parser.parse_term()
expected_ast = ('>', ('IDENTIFIER', 'age'), ('NUMBER', 18))
self.assertEqual(ast, expected_ast)
def test_parse(self):
tokens = [
('IF', 'IF'),
('IDENTIFIER', 'age'),
('>', '>'),
('NUMBER', '18'),
('AND', 'AND'),
('IDENTIFIER', 'gender'),
('==', '=='),
('STRING', '"male"'),
('THEN', 'THEN'),
('IDENTIFIER', 'is_eligible'),
('=', '='),
('IDENTIFIER', 'true')
]
parser = Parser(tokens)
ast = parser.parse()
expected_ast = (
'IF',
('AND',
('>', ('IDENTIFIER', 'age'), ('NUMBER', 18)),
('==', ('IDENTIFIER', 'gender'), ('STRING', 'male'))
),
('=', ('IDENTIFIER', 'is_eligible'), ('IDENTIFIER', 'true'))
)
self.assertEqual(ast, expected_ast)
class TestRuleParser(unittest.TestCase):
def test_parse(self):
rule_dsl = 'IF age > 18 AND gender == "male" THEN is_eligible = true'
rule_parser = RuleParser(rule_dsl)
rule_parser.parse()
expected_ast = (
'IF',
('AND',
('>', ('IDENTIFIER', 'age'), ('NUMBER', 18)),
('==', ('IDENTIFIER', 'gender'), ('STRING', 'male'))
),
('=', ('IDENTIFIER', 'is_eligible'), ('IDENTIFIER', 'true'))
)
self.assertEqual(rule_parser.ast, expected_ast)
if __name__ == '__main__':
unittest.main()