Skip to content

Commit

Permalink
Add a complete ast expression test
Browse files Browse the repository at this point in the history
And fix missing bits in the ast expression evaluator:

* boolean conversion
* & and | bit operators
  • Loading branch information
cvaroqui committed Jul 11, 2017
1 parent 1709c2b commit ef82a45
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/rcUtilities.py
Expand Up @@ -23,6 +23,8 @@
ast.Mult: op.mul,
ast.Div: op.truediv,
ast.Pow: op.pow,
ast.BitOr: op.or_,
ast.BitAnd: op.and_,
ast.BitXor: op.xor,
ast.USub: op.neg,
ast.FloorDiv: op.floordiv,
Expand All @@ -41,11 +43,14 @@ def eval_expr(expr):
""" arithmetic expressions evaluator
"""
def eval_(node):
_safe_names = {'None': None, 'True': True, 'False': False}
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.Str):
return node.s
elif isinstance(node, ast.Name):
if node.id in _safe_names:
return _safe_names[node.id]
return node.id
elif isinstance(node, ast.Tuple):
return tuple(node.elts)
Expand Down
32 changes: 32 additions & 0 deletions lib/tests/test_expr.py
@@ -0,0 +1,32 @@
from __future__ import print_function
from rcUtilities import eval_expr

def test_expr():
expressions = (
("1+2", 3),
("a+b", "ab"),
("a+'b'", "ab"),
("a in (a, b, 1)", True),
("a in (b, 1)", False),
("a == b", False),
("a == a", True),
("0 == 0", True),
("0 == 1", False),
("0 > 1", False),
("0 < 1", True),
("0 >= 0", True),
("1 >= 0", True),
("1 <= 0", False),
("0 <= 0", True),
("False and False", False),
("True and False", False),
("True and True", True),
("True or False", True),
("True or True", True),
("False or False", False),
("0 & 1", False),
)
for expr, expected in expressions:
result = eval_expr(expr)
print(expr, "=>", result, "expect:", expected)
assert result == expected

0 comments on commit ef82a45

Please sign in to comment.