-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_parser.py
65 lines (47 loc) · 1.96 KB
/
test_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
from parser import *
def ln(value):
return LiteralNode(value)
def bn(l, op:BinaryOp, r):
return BinaryOpNode(l, op, r)
def lparen():
return Token('(', TokenVariant.OPEN_PAREN)
def rparen():
return Token(')', TokenVariant.CLOSE_PAREN)
def test_literal():
assert ln(3).eval() == 3
assert ln(0).eval() == 0
def test_add():
assert bn(ln(3), BinaryOp.ADD, ln(4)).eval() == 7
assert bn(ln(3), BinaryOp.ADD, bn(ln(4), BinaryOp.SUB, ln(5))).eval() == 2
def test_parse_literal():
tokens = tokenize('3')
assert parse(tokens) == ln(3)
tokens = tokenize(' 3.14 ')
assert parse(tokens) == ln(3.14)
def test_parse_addition():
tokens = tokenize('3+4')
assert parse(tokens) == bn(ln(3), BinaryOp.ADD, ln(4))
def test_parse_three_additions():
tokens = tokenize('3+4+5')
assert parse(tokens) == bn(bn(ln(3), BinaryOp.ADD, ln(4)), BinaryOp.ADD, ln(5))
def test_parse_add_and_sub():
assert parse(tokenize('3+4-5')) == bn(bn(ln(3), BinaryOp.ADD, ln(4)), BinaryOp.SUB, ln(5))
assert parse(tokenize('3-4+5')) == bn(bn(ln(3), BinaryOp.SUB, ln(4)), BinaryOp.ADD, ln(5))
def test_parse_literal_in_parens():
tokens = tokenize('(3)')
assert parse(tokens) == ln(3)
def test_parse_expr_in_parens():
tokens = tokenize('(3+4)')
assert parse(tokens) == bn(ln(3), BinaryOp.ADD, ln(4))
def test_literal_op_parens():
tokens = tokenize('3 - (4 + 5)')
assert parse(tokens) == bn(ln(3), BinaryOp.SUB, bn(ln(4), BinaryOp.ADD, ln(5)))
def test_parens_op_literal():
tokens = tokenize('(3 - 4) + 5')
assert parse(tokens) == bn(bn(ln(3), BinaryOp.SUB, ln(4)), BinaryOp.ADD, ln(5))
def test_parse_add_sub_mul_div():
assert parse(tokenize('3+4/5')) == bn(ln(3), BinaryOp.ADD, bn(ln(4), BinaryOp.DIV, ln(5)))
def test_parse_add_sub_mul_div_add():
result = parse(tokenize('3-4/5+6'))
answer = result.eval()
assert result == bn(bn(ln(3), BinaryOp.SUB, bn(ln(4), BinaryOp.DIV, ln(5))), BinaryOp.ADD, ln(6))