Skip to content

Commit

Permalink
fixed the order of calling the callbacks + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pomponchik committed Jan 16, 2024
1 parent 1b9797b commit 8a2c1a5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cantok/tokens/condition_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
51 changes: 51 additions & 0 deletions tests/units/tokens/test_condition_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

0 comments on commit 8a2c1a5

Please sign in to comment.