Merge lp:~stub/charm-helpers/hook-magic into lp:charm-helpers

Proposed by Stuart Bishop
Status: Merged
Merged at revision: 40
Proposed branch: lp:~stub/charm-helpers/hook-magic
Merge into: lp:charm-helpers
Diff against target: 35 lines (+18/-0)
2 files modified
charmhelpers/core/hookenv.py (+3/-0)
tests/core/test_hookenv.py (+15/-0)
To merge this branch: bzr merge lp:~stub/charm-helpers/hook-magic
Reviewer Review Type Date Requested Status
James Page Approve
Review via email: mp+172109@code.launchpad.net

Description of the change

If an explicit hook name is not provided, register the function with both the function name and the function name with underscores replaced with hyphens. This allows the following to work as you would expect:

@hooks.hook()
def upgrade_charm():
    pass

I can only see this magic causing hassles in pathalogical situations (eg. two relations with names only differing by hypen or underscore choice), but is easily worked around by using an explicit hook name.

To post a comment you must log in.
Revision history for this message
James Page (james-page) wrote :

Hi Stuart

Looks good - aside from one minor lint issue:

tests/core/test_hookenv.py:712:9: E301 expected 1 blank line, found 0

However its more work for you to update that and resubmit than me just to fix it on merge.

+1

review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'charmhelpers/core/hookenv.py'
2--- charmhelpers/core/hookenv.py 2013-06-20 08:32:11 +0000
3+++ charmhelpers/core/hookenv.py 2013-06-28 17:13:28 +0000
4@@ -331,5 +331,8 @@
5 self.register(hook_name, decorated)
6 else:
7 self.register(decorated.__name__, decorated)
8+ if '_' in decorated.__name__:
9+ self.register(
10+ decorated.__name__.replace('_', '-'), decorated)
11 return decorated
12 return wrapper
13
14=== modified file 'tests/core/test_hookenv.py'
15--- tests/core/test_hookenv.py 2013-06-20 08:53:31 +0000
16+++ tests/core/test_hookenv.py 2013-06-28 17:13:28 +0000
17@@ -697,3 +697,18 @@
18 self.assertRaises(hookenv.UnregisteredHookError, hooks.execute,
19 ['brew'])
20 self.assertEqual(execs, [True])
21+
22+ def test_magic_underscores(self):
23+ # Juju hook names use hypens as separators. Python functions use
24+ # underscores. If explicit names have not been provided, hooks
25+ # are registered with both the function name and the function
26+ # name with underscores replaced with hypens for convenience.
27+ execs = []
28+ hooks = hookenv.Hooks()
29+ @hooks.hook()
30+ def call_me_maybe():
31+ execs.append(True)
32+
33+ hooks.execute(['call-me-maybe'])
34+ hooks.execute(['call_me_maybe'])
35+ self.assertEqual(execs, [True, True])

Subscribers

People subscribed via source and target branches