Skip to content

Commit

Permalink
Properly sort hook w.r.t. the order
Browse files Browse the repository at this point in the history
  • Loading branch information
timofurrer committed Oct 23, 2020
1 parent 0d7e007 commit 4dc976a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
23 changes: 13 additions & 10 deletions src/radish/hookregistry.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,15 @@ def __ge__(self, other):
return self.order >= other.order


class GeneratorHookImpl(HookImpl):
class GeneratorHookImpl:
"""Specialized Hook Implementation for Generator Hooks
A Generator Hook uses a yield statement to separate
the `before` and `after` part of a Hook.
"""

def __init__(self, what, func, on_tags, order, is_formatter=False, always=False):
super().__init__(what, None, func, on_tags, order, is_formatter, always)

def __init__(self, func):
self.func = func
self.generator = None

def __call__(self, *args, **kwargs):
Expand Down Expand Up @@ -145,22 +144,26 @@ def register(
"""Register the given Hook for later execution"""
if inspect.isgeneratorfunction(func):
# the registered function is a generator hook
hook_impl = GeneratorHookImpl(
what, func, on_tags, order, is_formatter, always
generator_hook = GeneratorHookImpl(func)
before_hook_impl = HookImpl(
what, "before", generator_hook, on_tags, order, is_formatter, always
)
after_hook_impl = HookImpl(
what, "after", generator_hook, on_tags, order * -1, is_formatter, always
)

if (
hook_impl in self._hooks["before"][what]
and hook_impl in self._hooks["after"][what]
before_hook_impl in self._hooks["before"][what]
and after_hook_impl in self._hooks["after"][what]
):
# NOTE: allow a Hook Implementation to be registered multiple times.
# This can happend when one hook module imports another in the same
# RADISH_BASEDIR.
return

# insert the HookImpl in the order given by ``order``.
bisect.insort_right(self._hooks["before"][what], hook_impl)
bisect.insort_right(self._hooks["after"][what], hook_impl)
bisect.insort_right(self._hooks["before"][what], before_hook_impl)
bisect.insort_right(self._hooks["after"][what], after_hook_impl)
else:
# we have regular hook
hook_impl = HookImpl(what, when, func, on_tags, order, is_formatter, always)
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_hookregistry.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def func(x, y, foo=None):
foo += 1
yield x, y, foo

hook = GeneratorHookImpl("what", func, [], 1)
hook = GeneratorHookImpl(func)

# when
first_x, first_y, first_foo = hook(1, 2, foo=3)
Expand Down

0 comments on commit 4dc976a

Please sign in to comment.