Skip to content

Commit 2a1e1fb

Browse files
sergioisidoroalexchamberlain
authored andcommitted
Support for init_app
Fixes: #24
1 parent 8d3ad24 commit 2a1e1fb

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

github_webhook/webhook.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,20 @@ class Webhook(object):
1616
:param secret: Optional secret, used to authenticate the hook comes from Github
1717
"""
1818

19-
def __init__(self, app, endpoint="/postreceive", secret=None):
20-
app.add_url_rule(rule=endpoint, endpoint=endpoint, view_func=self._postreceive, methods=["POST"])
19+
def __init__(self, app=None, endpoint="/postreceive", secret=None):
20+
self.app = app
21+
self.set_secret(secret)
22+
if app is not None:
23+
self.init_app(app, endpoint, secret)
2124

25+
def init_app(self, app, endpoint="/postreceive", secret=None):
2226
self._hooks = collections.defaultdict(list)
2327
self._logger = logging.getLogger("webhook")
28+
if secret is not None:
29+
self.set_secret(secret)
30+
app.add_url_rule(rule=endpoint, endpoint=endpoint, view_func=self._postreceive, methods=["POST"])
31+
32+
def set_secret(self, secret=None):
2433
if secret is not None and not isinstance(secret, six.binary_type):
2534
secret = secret.encode("utf-8")
2635
self._secret = secret

tests/test_webhook.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,44 @@ def test_constructor():
6565
)
6666

6767

68+
def test_init_app_flow():
69+
# GIVEN
70+
app = mock.Mock()
71+
72+
# WHEN
73+
webhook = Webhook()
74+
webhook.init_app(app)
75+
76+
# THEN
77+
app.add_url_rule.assert_called_once_with(
78+
endpoint="/postreceive", rule="/postreceive", view_func=webhook._postreceive, methods=["POST"]
79+
)
80+
81+
82+
def test_init_app_flow_should_not_accidentally_override_secrets():
83+
# GIVEN
84+
app = mock.Mock()
85+
86+
# WHEN
87+
webhook = Webhook(secret="hello-world-of-secrecy")
88+
webhook.init_app(app)
89+
90+
# THEN
91+
assert webhook._secret is not None
92+
93+
94+
def test_init_app_flow_should_override_secrets():
95+
# GIVEN
96+
app = mock.Mock()
97+
98+
# WHEN
99+
webhook = Webhook(secret="hello-world-of-secrecy")
100+
webhook.init_app(app, secret="a-new-world-of-secrecy")
101+
102+
# THEN
103+
assert webhook._secret == "a-new-world-of-secrecy".encode("utf-8")
104+
105+
68106
def test_run_push_hook(webhook, handler, push_request):
69107
# WHEN
70108
webhook._postreceive()

0 commit comments

Comments
 (0)