Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# define the function we'll send to the eval'er
def load_file(filename):
""" load a file and return its contents """
with open(filename) as f2:
return f2.read()
# simple load:
self.s.functions = {"read": load_file}
self.t("read('testfile.txt')", "42")
# and we should have *replaced* the default functions. Let's check:
with self.assertRaises(simpleeval.FunctionNotDefined):
self.t("int(read('testfile.txt'))", 42)
# OK, so we can load in the default functions as well...
self.s.functions.update(simpleeval.DEFAULT_FUNCTIONS)
# now it works:
self.t("int(read('testfile.txt'))", 42)
os.remove('testfile.txt')
def test_functionnotdefined(self):
try:
raise FunctionNotDefined("foo", "foo in bar")
except FunctionNotDefined as e:
assert hasattr(e, 'func_name')
assert getattr(e, 'func_name') == 'foo'
assert hasattr(e, 'expression')
assert getattr(e, 'expression') == 'foo in bar'
def test_use_func(self):
self.s = EvalWithCompoundTypes(functions={"map": map, "str": str})
self.t('list(map(str, [-1, 0, 1]))', ['-1', '0', '1'])
with self.assertRaises(NameNotDefined):
self.s.eval('list(map(bad, [-1, 0, 1]))')
with self.assertRaises(FunctionNotDefined):
self.s.eval('dir(str)')
with self.assertRaises(FeatureNotAvailable):
self.s.eval('str.__dict__')
self.s = EvalWithCompoundTypes(functions={"dir": dir, "str": str})
self.t('dir(str)', dir(str))
def test_functionnotdefined(self):
try:
raise FunctionNotDefined("foo", "foo in bar")
except FunctionNotDefined as e:
assert hasattr(e, 'func_name')
assert getattr(e, 'func_name') == 'foo'
assert hasattr(e, 'expression')
assert getattr(e, 'expression') == 'foo in bar'
def _eval_call(self, node):
if isinstance(node.func, ast.Attribute):
func = self._eval(node.func)
else:
try:
func = self.functions[node.func.id]
except KeyError:
raise FunctionNotDefined(node.func.id, self.expr)
except AttributeError as e:
raise FeatureNotAvailable('Lambda Functions not implemented')
if func in DISALLOW_FUNCTIONS:
raise FeatureNotAvailable('This function is forbidden')
return func(
*(self._eval(a) for a in node.args),
**dict(self._eval(k) for k in node.keywords)
)