43 lines
998 B
Python
43 lines
998 B
Python
from safe_eval import evaluate
|
|
|
|
cases = [
|
|
("2+3*4", 14),
|
|
("(2+3)*4", 20),
|
|
("2**3**2", 512), # right assoc
|
|
("10//3", 3),
|
|
("10%3", 1),
|
|
("-5+2", -3),
|
|
("abs(-7)", 7),
|
|
("min(3,1,2)", 1),
|
|
("max(3,1,2)", 3),
|
|
("round(2.5)", 2), # banker's? python round
|
|
("sqrt(16)+pi*0", 4.0),
|
|
("2.5*2", 5.0),
|
|
("log(e)", 1.0),
|
|
("sin(0)", 0.0),
|
|
]
|
|
for e, exp in cases:
|
|
got = evaluate(e)
|
|
assert got == exp, (e, got, exp)
|
|
print("OK", e, "=", got)
|
|
|
|
# error cases
|
|
errs = ["", "1/0", "import os", "x+1", "__import__('os')", "1 +", "(1+2", "f(1)"]
|
|
for e in errs:
|
|
try:
|
|
evaluate(e)
|
|
print("FAIL no error:", repr(e))
|
|
sys.exit(1)
|
|
except ValueError:
|
|
print("ERR-OK", repr(e))
|
|
|
|
# injection attempts
|
|
for bad in ["__builtins__", "eval('1')", "().__class__"]:
|
|
try:
|
|
evaluate(bad)
|
|
print("FAIL no error:", repr(bad)); sys.exit(1)
|
|
except ValueError:
|
|
print("INJ-OK", repr(bad))
|
|
|
|
print("ALL TESTS PASSED")
|