Skip to content

Commit

Permalink
more tests and updates for exception handling
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Sep 23, 2024
1 parent 84ab7d7 commit 36dc5f1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
19 changes: 13 additions & 6 deletions asteval/asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):

err = ExceptionHolder(node, exc=exc, msg=msg, expr=self.expr, lineno=lineno)
self._interrupt = ast.Raise()

self.error.append(err)
if self.error_msg is None:
self.error_msg = msg
Expand Down Expand Up @@ -301,14 +302,19 @@ def run(self, node, expr=None, lineno=None, with_raise=True):

# avoid too many repeated error messages (yes, this needs to be "2")
if len(self.error) > 2:
error = [self.error[0]]
for err in self.error[1:]:
le = error[-1]
if err.exc != le.exc or err.expr != le.expr or err.msg != le.msg:
error.append(err)
self.error = error
self._remove_duplicate_errors()

return None

def _remove_duplicate_errors(self):
"""remove duplicate exceptions"""
error = [self.error[0]]
for err in self.error[1:]:
lerr = error[-1]
if err.exc != lerr.exc or err.expr != lerr.expr or err.msg != lerr.msg:
error.append(err)
self.error = error

def __call__(self, expr, **kw):
"""Call class instance as function."""
return self.eval(expr, **kw)
Expand Down Expand Up @@ -343,6 +349,7 @@ def eval(self, expr, lineno=0, show_errors=True, raise_errors=False):
errmsg = self.error[-1].get_error()[1]
print(errmsg, file=self.err_writer)
if raise_errors and len(self.error) > 0:
self._remove_duplicate_errors()
err = self.error[-1]
raise err.exc(err.get_error()[1])
return None
Expand Down
2 changes: 2 additions & 0 deletions tests/test_asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1541,6 +1541,8 @@ def test_raise_errors_unknown_symbol(nested):
except NameError:
saw_exception = True
assert saw_exception
assert len(interp.error) > 0
assert interp.error[0].exc == NameError


@pytest.mark.parametrize("nested", [False, True])
Expand Down

0 comments on commit 36dc5f1

Please sign in to comment.