Files

47 lines
1.1 KiB
Python

from safe_eval import evaluate
import sys
cases = [
("2+3*4", 14),
("(2+3)*4", 20),
("2**3**2", 512), # right assoc
("-2**2", -4), # unary lower than **
("2**-2", 0.25), # signed exponent
("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))
raise AssertionError("test failed")
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)); raise AssertionError("test failed")
except ValueError:
print("INJ-OK", repr(bad))
print("ALL TESTS PASSED")