diff --git a/cantok/tokens/condition_token.py b/cantok/tokens/condition_token.py index 37d62eb..91ad2c9 100644 --- a/cantok/tokens/condition_token.py +++ b/cantok/tokens/condition_token.py @@ -24,14 +24,16 @@ def superpower(self) -> bool: return result else: + result = self.default + with suppress(Exception): self.before() with suppress(Exception): - return self.run_function() + result = self.run_function() with suppress(Exception): self.after() - return self.default + return result def run_function(self) -> bool: result = self.function() diff --git a/tests/units/tokens/test_condition_token.py b/tests/units/tokens/test_condition_token.py index 867ed7a..ad5f960 100644 --- a/tests/units/tokens/test_condition_token.py +++ b/tests/units/tokens/test_condition_token.py @@ -219,3 +219,54 @@ async def runner(): finish_time = perf_counter() assert finish_time - start_time >= timeout + + +def test_order_of_callbacks(): + lst = [] + token = ConditionToken(lambda: lst.append(2) is not None, before=lambda: lst.append(1), after=lambda: lst.append(3)) + + token.check() + + assert lst == [1, 2, 3] + + +@pytest.mark.parametrize( + 'options', + [ + {}, + {'suppress_exceptions': True} + ], +) +def test_raise_suppressed_exception_in_before_callback(options): + lst = [] + + def before_callback(): + lst.append(1) + raise ValueError + + token = ConditionToken(lambda: lst.append(2) is not None, before=before_callback, after=lambda: lst.append(3), **options) + + token.check() + + assert lst == [1, 2, 3] + + +@pytest.mark.parametrize( + 'options', + [ + {}, + {'suppress_exceptions': True} + ], +) +def test_raise_suppressed_exception_in_after_callback(options): + lst = [] + + def after_callback(): + lst.append(3) + raise ValueError + + token = ConditionToken(lambda: lst.append(2) is not None, before=lambda: lst.append(1), after=after_callback, **options) + + token.check() + + assert lst == [1, 2, 3]