##// END OF EJS Templates
webhook: enable support of extra repo variables as replacement in template url.
marcink -
r1761:8612110c default
parent child Browse files
Show More
@@ -1,265 +1,272 b''
1 1 # Copyright (C) 2016-2017 RhodeCode GmbH
2 2 #
3 3 # This program is free software: you can redistribute it and/or modify
4 4 # it under the terms of the GNU Affero General Public License, version 3
5 5 # (only), as published by the Free Software Foundation.
6 6 #
7 7 # This program is distributed in the hope that it will be useful,
8 8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 10 # GNU General Public License for more details.
11 11 #
12 12 # You should have received a copy of the GNU Affero General Public License
13 13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 14 #
15 15 # This program is dual-licensed. If you wish to learn more about the
16 16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18 18
19 import collections
19 20 import logging
20 21
21 22 from rhodecode.translation import lazy_ugettext
22 23 from rhodecode.model.db import User, Repository, Session
23 24 from rhodecode.events.base import RhodecodeEvent
24 25 from rhodecode.lib.vcs.exceptions import CommitDoesNotExistError
25 26
26 27 log = logging.getLogger(__name__)
27 28
28 29
29 30 def _commits_as_dict(commit_ids, repos):
30 31 """
31 32 Helper function to serialize commit_ids
32 33
33 34 :param commit_ids: commits to get
34 35 :param repos: list of repos to check
35 36 """
36 37 from rhodecode.lib.utils2 import extract_mentioned_users
37 38 from rhodecode.lib import helpers as h
38 39 from rhodecode.lib.helpers import (
39 40 urlify_commit_message, process_patterns, chop_at_smart)
40 41
41 42 if not repos:
42 43 raise Exception('no repo defined')
43 44
44 45 if not isinstance(repos, (tuple, list)):
45 46 repos = [repos]
46 47
47 48 if not commit_ids:
48 49 return []
49 50
50 51 needed_commits = list(commit_ids)
51 52
52 53 commits = []
53 54 reviewers = []
54 55 for repo in repos:
55 56 if not needed_commits:
56 57 return commits # return early if we have the commits we need
57 58
58 59 vcs_repo = repo.scm_instance(cache=False)
59 60 try:
60 61 # use copy of needed_commits since we modify it while iterating
61 62 for commit_id in list(needed_commits):
62 63 try:
63 64 cs = vcs_repo.get_changeset(commit_id)
64 65 except CommitDoesNotExistError:
65 66 continue # maybe its in next repo
66 67
67 68 cs_data = cs.__json__()
68 69 cs_data['mentions'] = extract_mentioned_users(cs_data['message'])
69 70 cs_data['reviewers'] = reviewers
70 71 cs_data['url'] = h.url('changeset_home',
71 72 repo_name=repo.repo_name,
72 73 revision=cs_data['raw_id'],
73 74 qualified=True
74 75 )
75 76 urlified_message, issues_data = process_patterns(
76 77 cs_data['message'], repo.repo_name)
77 78 cs_data['issues'] = issues_data
78 cs_data['message_html'] = urlify_commit_message(cs_data['message'],
79 repo.repo_name)
80 cs_data['message_html_title'] = chop_at_smart(cs_data['message'], '\n', suffix_if_chopped='...')
79 cs_data['message_html'] = urlify_commit_message(
80 cs_data['message'], repo.repo_name)
81 cs_data['message_html_title'] = chop_at_smart(
82 cs_data['message'], '\n', suffix_if_chopped='...')
81 83 commits.append(cs_data)
82 84
83 85 needed_commits.remove(commit_id)
84 86
85 87 except Exception as e:
86 88 log.exception(e)
87 89 # we don't send any commits when crash happens, only full list
88 90 # matters we short circuit then.
89 91 return []
90 92
91 93 missing_commits = set(commit_ids) - set(c['raw_id'] for c in commits)
92 94 if missing_commits:
93 95 log.error('missing commits: %s' % ', '.join(missing_commits))
94 96
95 97 return commits
96 98
97 99
98 100 def _issues_as_dict(commits):
99 101 """ Helper function to serialize issues from commits """
100 102 issues = {}
101 103 for commit in commits:
102 104 for issue in commit['issues']:
103 105 issues[issue['id']] = issue
104 106 return issues
105 107
106 108
107 109 class RepoEvent(RhodecodeEvent):
108 110 """
109 111 Base class for events acting on a repository.
110 112
111 113 :param repo: a :class:`Repository` instance
112 114 """
113 115
114 116 def __init__(self, repo):
115 117 super(RepoEvent, self).__init__()
116 118 self.repo = repo
117 119
118 120 def as_dict(self):
119 121 from rhodecode.model.repo import RepoModel
120 122 data = super(RepoEvent, self).as_dict()
123 extra_fields = collections.OrderedDict()
124 for field in self.repo.extra_fields:
125 extra_fields[field.field_key] = field.field_value
126
121 127 data.update({
122 128 'repo': {
123 129 'repo_id': self.repo.repo_id,
124 130 'repo_name': self.repo.repo_name,
125 131 'repo_type': self.repo.repo_type,
126 'url': RepoModel().get_url(self.repo)
132 'url': RepoModel().get_url(self.repo),
133 'extra_fields': extra_fields
127 134 }
128 135 })
129 136 return data
130 137
131 138
132 139 class RepoPreCreateEvent(RepoEvent):
133 140 """
134 141 An instance of this class is emitted as an :term:`event` before a repo is
135 142 created.
136 143 """
137 144 name = 'repo-pre-create'
138 145 display_name = lazy_ugettext('repository pre create')
139 146
140 147
141 148 class RepoCreateEvent(RepoEvent):
142 149 """
143 150 An instance of this class is emitted as an :term:`event` whenever a repo is
144 151 created.
145 152 """
146 153 name = 'repo-create'
147 154 display_name = lazy_ugettext('repository created')
148 155
149 156
150 157 class RepoPreDeleteEvent(RepoEvent):
151 158 """
152 159 An instance of this class is emitted as an :term:`event` whenever a repo is
153 160 created.
154 161 """
155 162 name = 'repo-pre-delete'
156 163 display_name = lazy_ugettext('repository pre delete')
157 164
158 165
159 166 class RepoDeleteEvent(RepoEvent):
160 167 """
161 168 An instance of this class is emitted as an :term:`event` whenever a repo is
162 169 created.
163 170 """
164 171 name = 'repo-delete'
165 172 display_name = lazy_ugettext('repository deleted')
166 173
167 174
168 175 class RepoVCSEvent(RepoEvent):
169 176 """
170 177 Base class for events triggered by the VCS
171 178 """
172 179 def __init__(self, repo_name, extras):
173 180 self.repo = Repository.get_by_repo_name(repo_name)
174 181 if not self.repo:
175 182 raise Exception('repo by this name %s does not exist' % repo_name)
176 183 self.extras = extras
177 184 super(RepoVCSEvent, self).__init__(self.repo)
178 185
179 186 @property
180 187 def actor(self):
181 188 if self.extras.get('username'):
182 189 return User.get_by_username(self.extras['username'])
183 190
184 191 @property
185 192 def actor_ip(self):
186 193 if self.extras.get('ip'):
187 194 return self.extras['ip']
188 195
189 196 @property
190 197 def server_url(self):
191 198 if self.extras.get('server_url'):
192 199 return self.extras['server_url']
193 200
194 201
195 202 class RepoPrePullEvent(RepoVCSEvent):
196 203 """
197 204 An instance of this class is emitted as an :term:`event` before commits
198 205 are pulled from a repo.
199 206 """
200 207 name = 'repo-pre-pull'
201 208 display_name = lazy_ugettext('repository pre pull')
202 209
203 210
204 211 class RepoPullEvent(RepoVCSEvent):
205 212 """
206 213 An instance of this class is emitted as an :term:`event` after commits
207 214 are pulled from a repo.
208 215 """
209 216 name = 'repo-pull'
210 217 display_name = lazy_ugettext('repository pull')
211 218
212 219
213 220 class RepoPrePushEvent(RepoVCSEvent):
214 221 """
215 222 An instance of this class is emitted as an :term:`event` before commits
216 223 are pushed to a repo.
217 224 """
218 225 name = 'repo-pre-push'
219 226 display_name = lazy_ugettext('repository pre push')
220 227
221 228
222 229 class RepoPushEvent(RepoVCSEvent):
223 230 """
224 231 An instance of this class is emitted as an :term:`event` after commits
225 232 are pushed to a repo.
226 233
227 234 :param extras: (optional) dict of data from proxied VCS actions
228 235 """
229 236 name = 'repo-push'
230 237 display_name = lazy_ugettext('repository push')
231 238
232 239 def __init__(self, repo_name, pushed_commit_ids, extras):
233 240 super(RepoPushEvent, self).__init__(repo_name, extras)
234 241 self.pushed_commit_ids = pushed_commit_ids
235 242
236 243 def as_dict(self):
237 244 data = super(RepoPushEvent, self).as_dict()
238 245 branch_url = repo_url = data['repo']['url']
239 246
240 247 commits = _commits_as_dict(
241 248 commit_ids=self.pushed_commit_ids, repos=[self.repo])
242 249
243 250 last_branch = None
244 251 for commit in reversed(commits):
245 252 commit['branch'] = commit['branch'] or last_branch
246 253 last_branch = commit['branch']
247 254 issues = _issues_as_dict(commits)
248 255
249 256 branches = set(
250 257 commit['branch'] for commit in commits if commit['branch'])
251 258 branches = [
252 259 {
253 260 'name': branch,
254 261 'url': '{}/changelog?branch={}'.format(
255 262 data['repo']['url'], branch)
256 263 }
257 264 for branch in branches
258 265 ]
259 266
260 267 data['push'] = {
261 268 'commits': commits,
262 269 'issues': issues,
263 270 'branches': branches,
264 271 }
265 272 return data
@@ -1,271 +1,277 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2012-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 from __future__ import unicode_literals
22 22 import string
23 23 from collections import OrderedDict
24 24
25 25 import deform
26 26 import logging
27 27 import requests
28 28 import colander
29 29 from celery.task import task
30 30 from requests.packages.urllib3.util.retry import Retry
31 31
32 32 from rhodecode import events
33 33 from rhodecode.translation import _
34 34 from rhodecode.integrations.types.base import IntegrationTypeBase
35 35
36 36 log = logging.getLogger(__name__)
37 37
38 38 # updating this required to update the `common_vars` passed in url calling func
39 39 WEBHOOK_URL_VARS = [
40 40 'repo_name',
41 41 'repo_type',
42 42 'repo_id',
43 43 'repo_url',
44 # extra repo fields
45 'extra:<extra_key_name>',
44 46
45 47 # special attrs below that we handle, using multi-call
46 48 'branch',
47 49 'commit_id',
48 50
49 51 # pr events vars
50 52 'pull_request_id',
51 53 'pull_request_url',
52 54
53 55 # user who triggers the call
54 56 'username',
55 57 'user_id',
56 58
57 59 ]
58 60 URL_VARS = ', '.join('${' + x + '}' for x in WEBHOOK_URL_VARS)
59 61
60 62
61 63 class WebhookHandler(object):
62 64 def __init__(self, template_url, secret_token):
63 65 self.template_url = template_url
64 66 self.secret_token = secret_token
65 67
66 68 def get_base_parsed_template(self, data):
67 69 """
68 70 initially parses the passed in template with some common variables
69 71 available on ALL calls
70 72 """
71 73 # note: make sure to update the `WEBHOOK_URL_VARS` if this changes
72 74 common_vars = {
73 75 'repo_name': data['repo']['repo_name'],
74 76 'repo_type': data['repo']['repo_type'],
75 77 'repo_id': data['repo']['repo_id'],
76 78 'repo_url': data['repo']['url'],
77 79 'username': data['actor']['username'],
78 80 'user_id': data['actor']['user_id']
79 81 }
82 extra_vars = {}
83 for extra_key, extra_val in data['repo']['extra_fields'].items():
84 extra_vars['extra:{}'.format(extra_key)] = extra_val
85 common_vars.update(extra_vars)
80 86
81 87 return string.Template(
82 88 self.template_url).safe_substitute(**common_vars)
83 89
84 90 def repo_push_event_handler(self, event, data):
85 91 url = self.get_base_parsed_template(data)
86 92 url_cals = []
87 93 branch_data = OrderedDict()
88 94 for obj in data['push']['branches']:
89 95 branch_data[obj['name']] = obj
90 96
91 97 branches_commits = OrderedDict()
92 98 for commit in data['push']['commits']:
93 99 if commit['branch'] not in branches_commits:
94 100 branch_commits = {'branch': branch_data[commit['branch']],
95 101 'commits': []}
96 102 branches_commits[commit['branch']] = branch_commits
97 103
98 104 branch_commits = branches_commits[commit['branch']]
99 105 branch_commits['commits'].append(commit)
100 106
101 107 if '${branch}' in url:
102 108 # call it multiple times, for each branch if used in variables
103 109 for branch, commit_ids in branches_commits.items():
104 110 branch_url = string.Template(url).safe_substitute(branch=branch)
105 111 # call further down for each commit if used
106 112 if '${commit_id}' in branch_url:
107 113 for commit_data in commit_ids['commits']:
108 114 commit_id = commit_data['raw_id']
109 115 commit_url = string.Template(branch_url).safe_substitute(
110 116 commit_id=commit_id)
111 117 # register per-commit call
112 118 log.debug(
113 119 'register webhook call(%s) to url %s', event, commit_url)
114 120 url_cals.append((commit_url, self.secret_token, data))
115 121
116 122 else:
117 123 # register per-branch call
118 124 log.debug(
119 125 'register webhook call(%s) to url %s', event, branch_url)
120 126 url_cals.append((branch_url, self.secret_token, data))
121 127
122 128 else:
123 129 log.debug(
124 130 'register webhook call(%s) to url %s', event, url)
125 131 url_cals.append((url, self.secret_token, data))
126 132
127 133 return url_cals
128 134
129 135 def repo_create_event_handler(self, event, data):
130 136 url = self.get_base_parsed_template(data)
131 137 log.debug(
132 138 'register webhook call(%s) to url %s', event, url)
133 139 return [(url, self.secret_token, data)]
134 140
135 141 def pull_request_event_handler(self, event, data):
136 142 url = self.get_base_parsed_template(data)
137 143 log.debug(
138 144 'register webhook call(%s) to url %s', event, url)
139 145 url = string.Template(url).safe_substitute(
140 146 pull_request_id=data['pullrequest']['pull_request_id'],
141 147 pull_request_url=data['pullrequest']['url'])
142 148 return [(url, self.secret_token, data)]
143 149
144 150 def __call__(self, event, data):
145 151 if isinstance(event, events.RepoPushEvent):
146 152 return self.repo_push_event_handler(event, data)
147 153 elif isinstance(event, events.RepoCreateEvent):
148 154 return self.repo_create_event_handler(event, data)
149 155 elif isinstance(event, events.PullRequestEvent):
150 156 return self.pull_request_event_handler(event, data)
151 157 else:
152 158 raise ValueError('event type not supported: %s' % events)
153 159
154 160
155 161 class WebhookSettingsSchema(colander.Schema):
156 162 url = colander.SchemaNode(
157 163 colander.String(),
158 164 title=_('Webhook URL'),
159 165 description=
160 166 _('URL of the webhook to receive POST event. Following variables '
161 167 'are allowed to be used: {vars}. Some of the variables would '
162 168 'trigger multiple calls, like ${{branch}} or ${{commit_id}}. '
163 169 'Webhook will be called as many times as unique objects in '
164 170 'data in such cases.').format(vars=URL_VARS),
165 171 missing=colander.required,
166 172 required=True,
167 173 validator=colander.url,
168 174 widget=deform.widget.TextInputWidget(
169 175 placeholder='https://www.example.com/webhook'
170 176 ),
171 177 )
172 178 secret_token = colander.SchemaNode(
173 179 colander.String(),
174 180 title=_('Secret Token'),
175 181 description=_('String used to validate received payloads.'),
176 182 default='',
177 183 missing='',
178 184 widget=deform.widget.TextInputWidget(
179 185 placeholder='secret_token'
180 186 ),
181 187 )
182 188 method_type = colander.SchemaNode(
183 189 colander.String(),
184 190 title=_('Call Method'),
185 191 description=_('Select if the webhook call should be made '
186 192 'with POST or GET.'),
187 193 default='post',
188 194 missing='',
189 195 widget=deform.widget.RadioChoiceWidget(
190 196 values=[('get', 'GET'), ('post', 'POST')],
191 197 inline=True
192 198 ),
193 199 )
194 200
195 201
196 202 class WebhookIntegrationType(IntegrationTypeBase):
197 203 key = 'webhook'
198 204 display_name = _('Webhook')
199 205 description = _('Post json events to a webhook endpoint')
200 206 icon = '''<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg viewBox="0 0 256 239" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" preserveAspectRatio="xMidYMid"><g><path d="M119.540432,100.502743 C108.930124,118.338815 98.7646301,135.611455 88.3876025,152.753617 C85.7226696,157.154315 84.4040417,160.738531 86.5332204,166.333309 C92.4107024,181.787152 84.1193605,196.825836 68.5350381,200.908244 C53.8383677,204.759349 39.5192953,195.099955 36.6032893,179.365384 C34.0194114,165.437749 44.8274148,151.78491 60.1824106,149.608284 C61.4694072,149.424428 62.7821041,149.402681 64.944891,149.240571 C72.469175,136.623655 80.1773157,123.700312 88.3025935,110.073173 C73.611854,95.4654658 64.8677898,78.3885437 66.803227,57.2292132 C68.1712787,42.2715849 74.0527146,29.3462646 84.8033863,18.7517722 C105.393354,-1.53572199 136.805164,-4.82141828 161.048542,10.7510424 C184.333097,25.7086706 194.996783,54.8450075 185.906752,79.7822957 C179.052655,77.9239597 172.151111,76.049808 164.563565,73.9917997 C167.418285,60.1274266 165.306899,47.6765751 155.95591,37.0109123 C149.777932,29.9690049 141.850349,26.2780332 132.835442,24.9178894 C114.764113,22.1877169 97.0209573,33.7983633 91.7563309,51.5355878 C85.7800012,71.6669027 94.8245623,88.1111998 119.540432,100.502743 L119.540432,100.502743 Z" fill="#C73A63"></path><path d="M149.841194,79.4106285 C157.316054,92.5969067 164.905578,105.982857 172.427885,119.246236 C210.44865,107.483365 239.114472,128.530009 249.398582,151.063322 C261.81978,178.282014 253.328765,210.520191 228.933162,227.312431 C203.893073,244.551464 172.226236,241.605803 150.040866,219.46195 C155.694953,214.729124 161.376716,209.974552 167.44794,204.895759 C189.360489,219.088306 208.525074,218.420096 222.753207,201.614016 C234.885769,187.277151 234.622834,165.900356 222.138374,151.863988 C207.730339,135.66681 188.431321,135.172572 165.103273,150.721309 C155.426087,133.553447 145.58086,116.521995 136.210101,99.2295848 C133.05093,93.4015266 129.561608,90.0209366 122.440622,88.7873178 C110.547271,86.7253555 102.868785,76.5124151 102.408155,65.0698097 C101.955433,53.7537294 108.621719,43.5249733 119.04224,39.5394355 C129.363912,35.5914599 141.476705,38.7783085 148.419765,47.554004 C154.093621,54.7244134 155.896602,62.7943365 152.911402,71.6372484 C152.081082,74.1025091 151.00562,76.4886916 149.841194,79.4106285 L149.841194,79.4106285 Z" fill="#4B4B4B"></path><path d="M167.706921,187.209935 L121.936499,187.209935 C117.54964,205.253587 108.074103,219.821756 91.7464461,229.085759 C79.0544063,236.285822 65.3738898,238.72736 50.8136292,236.376762 C24.0061432,232.053165 2.08568567,207.920497 0.156179306,180.745298 C-2.02835403,149.962159 19.1309765,122.599149 47.3341915,116.452801 C49.2814904,123.524363 51.2485589,130.663141 53.1958579,137.716911 C27.3195169,150.919004 18.3639187,167.553089 25.6054984,188.352614 C31.9811726,206.657224 50.0900643,216.690262 69.7528413,212.809503 C89.8327554,208.847688 99.9567329,192.160226 98.7211371,165.37844 C117.75722,165.37844 136.809118,165.180745 155.847178,165.475311 C163.280522,165.591951 169.019617,164.820939 174.620326,158.267339 C183.840836,147.48306 200.811003,148.455721 210.741239,158.640984 C220.88894,169.049642 220.402609,185.79839 209.663799,195.768166 C199.302587,205.38802 182.933414,204.874012 173.240413,194.508846 C171.247644,192.37176 169.677943,189.835329 167.706921,187.209935 L167.706921,187.209935 Z" fill="#4A4A4A"></path></g></svg>'''
201 207
202 208 valid_events = [
203 209 events.PullRequestCloseEvent,
204 210 events.PullRequestMergeEvent,
205 211 events.PullRequestUpdateEvent,
206 212 events.PullRequestCommentEvent,
207 213 events.PullRequestReviewEvent,
208 214 events.PullRequestCreateEvent,
209 215 events.RepoPushEvent,
210 216 events.RepoCreateEvent,
211 217 ]
212 218
213 219 def settings_schema(self):
214 220 schema = WebhookSettingsSchema()
215 221 schema.add(colander.SchemaNode(
216 222 colander.Set(),
217 223 widget=deform.widget.CheckboxChoiceWidget(
218 224 values=sorted(
219 225 [(e.name, e.display_name) for e in self.valid_events]
220 226 )
221 227 ),
222 228 description="Events activated for this integration",
223 229 name='events'
224 230 ))
225 231 return schema
226 232
227 233 def send_event(self, event):
228 234 log.debug('handling event %s with webhook integration %s',
229 235 event.name, self)
230 236
231 237 if event.__class__ not in self.valid_events:
232 238 log.debug('event not valid: %r' % event)
233 239 return
234 240
235 241 if event.name not in self.settings['events']:
236 242 log.debug('event ignored: %r' % event)
237 243 return
238 244
239 245 data = event.as_dict()
240 246 template_url = self.settings['url']
241 247
242 248 handler = WebhookHandler(template_url, self.settings['secret_token'])
243 249 url_calls = handler(event, data)
244 250 log.debug('webhook: calling following urls: %s',
245 251 [x[0] for x in url_calls])
246 252 post_to_webhook(url_calls, self.settings)
247 253
248 254
249 255 @task(ignore_result=True)
250 256 def post_to_webhook(url_calls, settings):
251 257 max_retries = 3
252 258 for url, token, data in url_calls:
253 259 # retry max N times
254 260 retries = Retry(
255 261 total=max_retries,
256 262 backoff_factor=0.15,
257 263 status_forcelist=[500, 502, 503, 504])
258 264 req_session = requests.Session()
259 265 req_session.mount(
260 266 'http://', requests.adapters.HTTPAdapter(max_retries=retries))
261 267
262 268 method = settings.get('method_type') or 'post'
263 269 call_method = getattr(req_session, method)
264 270
265 271 log.debug('calling WEBHOOK with method: %s', call_method)
266 272 resp = call_method(url, json={
267 273 'token': token,
268 274 'event': data
269 275 })
270 276 log.debug('Got WEBHOOK response: %s', resp)
271 277 resp.raise_for_status() # raise exception on a failed request
@@ -1,97 +1,98 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20
21 21 import pytest
22 22
23 23 from rhodecode import events
24 24 from rhodecode.lib.utils2 import AttributeDict
25 25 from rhodecode.integrations.types.webhook import WebhookHandler
26 26
27 27
28 28 @pytest.fixture
29 29 def base_data():
30 30 return {
31 31 'repo': {
32 32 'repo_name': 'foo',
33 33 'repo_type': 'hg',
34 34 'repo_id': '12',
35 35 'url': 'http://repo.url/foo',
36 'extra_fields': {},
36 37 },
37 38 'actor': {
38 39 'username': 'actor_name',
39 40 'user_id': 1
40 41 }
41 42 }
42 43
43 44
44 45 def test_webhook_parse_url_invalid_event():
45 46 template_url = 'http://server.com/${repo_name}/build'
46 47 handler = WebhookHandler(template_url, 'secret_token')
47 48 with pytest.raises(ValueError) as err:
48 49 handler(events.RepoDeleteEvent(''), {})
49 50 assert str(err.value).startswith('event type not supported')
50 51
51 52
52 53 @pytest.mark.parametrize('template,expected_urls', [
53 54 ('http://server.com/${repo_name}/build', ['http://server.com/foo/build']),
54 55 ('http://server.com/${repo_name}/${repo_type}', ['http://server.com/foo/hg']),
55 56 ('http://${server}.com/${repo_name}/${repo_id}', ['http://${server}.com/foo/12']),
56 57 ('http://server.com/${branch}/build', ['http://server.com/${branch}/build']),
57 58 ])
58 59 def test_webook_parse_url_for_create_event(base_data, template, expected_urls):
59 60 handler = WebhookHandler(template, 'secret_token')
60 61 urls = handler(events.RepoCreateEvent(''), base_data)
61 62 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
62 63
63 64
64 65 @pytest.mark.parametrize('template,expected_urls', [
65 66 ('http://server.com/${repo_name}/${pull_request_id}', ['http://server.com/foo/999']),
66 67 ('http://server.com/${repo_name}/${pull_request_url}', ['http://server.com/foo/http://pr-url.com']),
67 68 ])
68 69 def test_webook_parse_url_for_pull_request_event(base_data, template, expected_urls):
69 70 base_data['pullrequest'] = {
70 71 'pull_request_id': 999,
71 72 'url': 'http://pr-url.com',
72 73 }
73 74 handler = WebhookHandler(template, 'secret_token')
74 75 urls = handler(events.PullRequestCreateEvent(
75 76 AttributeDict({'target_repo': 'foo'})), base_data)
76 77 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
77 78
78 79
79 80 @pytest.mark.parametrize('template,expected_urls', [
80 81 ('http://server.com/${branch}/build', ['http://server.com/stable/build',
81 82 'http://server.com/dev/build']),
82 83 ('http://server.com/${branch}/${commit_id}', ['http://server.com/stable/stable-xxx',
83 84 'http://server.com/stable/stable-yyy',
84 85 'http://server.com/dev/dev-xxx',
85 86 'http://server.com/dev/dev-yyy']),
86 87 ])
87 88 def test_webook_parse_url_for_push_event(pylonsapp, repo_push_event, base_data, template, expected_urls):
88 89 base_data['push'] = {
89 90 'branches': [{'name': 'stable'}, {'name': 'dev'}],
90 91 'commits': [{'branch': 'stable', 'raw_id': 'stable-xxx'},
91 92 {'branch': 'stable', 'raw_id': 'stable-yyy'},
92 93 {'branch': 'dev', 'raw_id': 'dev-xxx'},
93 94 {'branch': 'dev', 'raw_id': 'dev-yyy'}]
94 95 }
95 96 handler = WebhookHandler(template, 'secret_token')
96 97 urls = handler(repo_push_event, base_data)
97 98 assert urls == [(url, 'secret_token', base_data) for url in expected_urls]
General Comments 0
You need to be logged in to leave comments. Login now