Files
seanlynch-srl-nodes/test_evaluator.py
Sean Lynch 3d6b2437d5 Mutate the AST and compile instead
As long as we only let nodes through that we believe to be safe, it
should be fine to let Python handle the execution. The main unsafe
piece of code is attribute lookup.

Right now this allows access to str.format. Need to fix that.
2023-09-30 18:26:45 -04:00

36 lines
896 B
Python

import unittest
from evaluator import evaluate, safe_vformat
class TestEvaluator(unittest.TestCase):
def test_fstring_access(self):
with self.assertRaises(ValueError):
evaluate("(lambda x: f'{x.__class__}')(1)")
def test_fstrings(self):
s = {"x": 5}
r = evaluate("f'{x}'", s)
self.assertEqual(r, "5")
r = evaluate("f'{x:05}'", s)
self.assertEqual(r, "00005")
def test_lambda(self):
r = evaluate("(lambda x, y: x + y)(2, 3)")
self.assertEqual(r, 5)
def test_attribute_access(self):
with self.assertRaises(ValueError):
evaluate("str.__class__")
class TestFormatter(unittest.TestCase):
def test_format_access(self):
with self.assertRaises(ValueError):
s = safe_vformat("{x.__class__}", [], {"x": object})
if __name__ == "__main__":
unittest.main()