##// END OF EJS Templates
tests: Add tests to check the shadow-repo regular expression.
Martin Bornhold -
r919:f10baf56 default
parent child Browse files
Show More
@@ -1,417 +1,451 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2010-2016 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 base64
22 22
23 23 import mock
24 24 import pytest
25 25 import webtest.app
26 26
27 27 from rhodecode.lib.caching_query import FromCache
28 28 from rhodecode.lib.hooks_daemon import DummyHooksCallbackDaemon
29 29 from rhodecode.lib.middleware import simplevcs
30 30 from rhodecode.lib.middleware.https_fixup import HttpsFixup
31 31 from rhodecode.lib.middleware.utils import scm_app
32 32 from rhodecode.model.db import User, _hash_key
33 33 from rhodecode.model.meta import Session
34 34 from rhodecode.tests import (
35 35 HG_REPO, TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
36 36 from rhodecode.tests.lib.middleware import mock_scm_app
37 37 from rhodecode.tests.utils import set_anonymous_access
38 38
39 39
40 40 class StubVCSController(simplevcs.SimpleVCS):
41 41
42 42 SCM = 'hg'
43 43 stub_response_body = tuple()
44 44
45 45 def __init__(self, *args, **kwargs):
46 46 super(StubVCSController, self).__init__(*args, **kwargs)
47 47 self._action = 'pull'
48 48 self._name = HG_REPO
49 49 self.set_repo_names(None)
50 50
51 51 def _get_repository_name(self, environ):
52 52 return self._name
53 53
54 54 def _get_action(self, environ):
55 55 return self._action
56 56
57 57 def _create_wsgi_app(self, repo_path, repo_name, config):
58 58 def fake_app(environ, start_response):
59 59 start_response('200 OK', [])
60 60 return self.stub_response_body
61 61 return fake_app
62 62
63 63 def _create_config(self, extras, repo_name):
64 64 return None
65 65
66 66
67 67 @pytest.fixture
68 68 def vcscontroller(pylonsapp, config_stub):
69 69 config_stub.testing_securitypolicy()
70 70 config_stub.include('rhodecode.authentication')
71 71
72 72 set_anonymous_access(True)
73 73 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
74 74 app = HttpsFixup(controller, pylonsapp.config)
75 75 app = webtest.app.TestApp(app)
76 76
77 77 _remove_default_user_from_query_cache()
78 78
79 79 # Sanity checks that things are set up correctly
80 80 app.get('/' + HG_REPO, status=200)
81 81
82 82 app.controller = controller
83 83 return app
84 84
85 85
86 86 def _remove_default_user_from_query_cache():
87 87 user = User.get_default_user(cache=True)
88 88 query = Session().query(User).filter(User.username == user.username)
89 89 query = query.options(FromCache(
90 90 "sql_cache_short", "get_user_%s" % _hash_key(user.username)))
91 91 query.invalidate()
92 92 Session().expire(user)
93 93
94 94
95 95 @pytest.fixture
96 96 def disable_anonymous_user(request, pylonsapp):
97 97 set_anonymous_access(False)
98 98
99 99 @request.addfinalizer
100 100 def cleanup():
101 101 set_anonymous_access(True)
102 102
103 103
104 104 def test_handles_exceptions_during_permissions_checks(
105 105 vcscontroller, disable_anonymous_user):
106 106 user_and_pass = '%s:%s' % (TEST_USER_ADMIN_LOGIN, TEST_USER_ADMIN_PASS)
107 107 auth_password = base64.encodestring(user_and_pass).strip()
108 108 extra_environ = {
109 109 'AUTH_TYPE': 'Basic',
110 110 'HTTP_AUTHORIZATION': 'Basic %s' % auth_password,
111 111 'REMOTE_USER': TEST_USER_ADMIN_LOGIN,
112 112 }
113 113
114 114 # Verify that things are hooked up correctly
115 115 vcscontroller.get('/', status=200, extra_environ=extra_environ)
116 116
117 117 # Simulate trouble during permission checks
118 118 with mock.patch('rhodecode.model.db.User.get_by_username',
119 119 side_effect=Exception) as get_user:
120 120 # Verify that a correct 500 is returned and check that the expected
121 121 # code path was hit.
122 122 vcscontroller.get('/', status=500, extra_environ=extra_environ)
123 123 assert get_user.called
124 124
125 125
126 126 def test_returns_forbidden_if_no_anonymous_access(
127 127 vcscontroller, disable_anonymous_user):
128 128 vcscontroller.get('/', status=401)
129 129
130 130
131 131 class StubFailVCSController(simplevcs.SimpleVCS):
132 132 def _handle_request(self, environ, start_response):
133 133 raise Exception("BOOM")
134 134
135 135
136 136 @pytest.fixture(scope='module')
137 137 def fail_controller(pylonsapp):
138 138 controller = StubFailVCSController(pylonsapp, pylonsapp.config, None)
139 139 controller = HttpsFixup(controller, pylonsapp.config)
140 140 controller = webtest.app.TestApp(controller)
141 141 return controller
142 142
143 143
144 144 def test_handles_exceptions_as_internal_server_error(fail_controller):
145 145 fail_controller.get('/', status=500)
146 146
147 147
148 148 def test_provides_traceback_for_appenlight(fail_controller):
149 149 response = fail_controller.get(
150 150 '/', status=500, extra_environ={'appenlight.client': 'fake'})
151 151 assert 'appenlight.__traceback' in response.request.environ
152 152
153 153
154 154 def test_provides_utils_scm_app_as_scm_app_by_default(pylonsapp):
155 155 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
156 156 assert controller.scm_app is scm_app
157 157
158 158
159 159 def test_allows_to_override_scm_app_via_config(pylonsapp):
160 160 config = pylonsapp.config.copy()
161 161 config['vcs.scm_app_implementation'] = (
162 162 'rhodecode.tests.lib.middleware.mock_scm_app')
163 163 controller = StubVCSController(pylonsapp, config, None)
164 164 assert controller.scm_app is mock_scm_app
165 165
166 166
167 167 @pytest.mark.parametrize('query_string, expected', [
168 168 ('cmd=stub_command', True),
169 169 ('cmd=listkeys', False),
170 170 ])
171 171 def test_should_check_locking(query_string, expected):
172 172 result = simplevcs._should_check_locking(query_string)
173 173 assert result == expected
174 174
175 175
176 class TestShadowRepoRegularExpression(object):
177 @pytest.mark.parametrize('url, expected', [
178 # repo with/without groups
179 ('My-Repo/pull-request/1/repository', True),
180 ('Group/My-Repo/pull-request/2/repository', True),
181 ('Group/Sub-Group/My-Repo/pull-request/3/repository', True),
182 ('Group/Sub-Group1/Sub-Group2/My-Repo/pull-request/3/repository', True),
183
184 # pull request ID
185 ('MyRepo/pull-request/1/repository', True),
186 ('MyRepo/pull-request/1234567890/repository', True),
187 ('MyRepo/pull-request/-1/repository', False),
188 ('MyRepo/pull-request/invalid/repository', False),
189
190 # unicode
191 (u'Sp€çîál-Repö/pull-request/1/repository', True),
192 (u'Sp€çîál-Gröüp/Sp€çîál-Repö/pull-request/1/repository', True),
193
194 # trailing/leading slash
195 ('/My-Repo/pull-request/1/repository', False),
196 ('My-Repo/pull-request/1/repository/', False),
197 ('/My-Repo/pull-request/1/repository/', False),
198
199 # misc
200 ('My-Repo/pull-request/1/repository/extra', False),
201 ('My-Repo/pull-request/1/repositoryextra', False),
202 ])
203 def test_shadow_repo_regular_expression(self, url, expected):
204 from rhodecode.lib.middleware.simplevcs import SimpleVCS
205 match_obj = SimpleVCS.shadow_repo_re.match(url)
206 assert (match_obj is not None) == expected
207
208
176 209 @pytest.mark.backends('git', 'hg')
177 210 class TestShadowRepoExposure(object):
211
178 212 def test_pull_on_shadow_repo_propagates_to_wsgi_app(self, pylonsapp):
179 213 """
180 214 Check that a pull action to a shadow repo is propagated to the
181 215 underlying wsgi app.
182 216 """
183 217 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
184 218 controller._check_ssl = mock.Mock()
185 219 controller.is_shadow_repo = True
186 220 controller._action = 'pull'
187 221 controller.stub_response_body = 'dummy body value'
188 222 environ_stub = {
189 223 'HTTP_HOST': 'test.example.com',
190 224 'REQUEST_METHOD': 'GET',
191 225 'wsgi.url_scheme': 'http',
192 226 }
193 227
194 228 response = controller(environ_stub, mock.Mock())
195 229 response_body = ''.join(response)
196 230
197 231 # Assert that we got the response from the wsgi app.
198 232 assert response_body == controller.stub_response_body
199 233
200 234 def test_push_on_shadow_repo_raises(self, pylonsapp):
201 235 """
202 236 Check that a push action to a shadow repo is aborted.
203 237 """
204 238 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
205 239 controller._check_ssl = mock.Mock()
206 240 controller.is_shadow_repo = True
207 241 controller._action = 'push'
208 242 controller.stub_response_body = 'dummy body value'
209 243 environ_stub = {
210 244 'HTTP_HOST': 'test.example.com',
211 245 'REQUEST_METHOD': 'GET',
212 246 'wsgi.url_scheme': 'http',
213 247 }
214 248
215 249 response = controller(environ_stub, mock.Mock())
216 250 response_body = ''.join(response)
217 251
218 252 assert response_body != controller.stub_response_body
219 253 # Assert that a 406 error is returned.
220 254 assert '406 Not Acceptable' in response_body
221 255
222 256 def test_set_repo_names_no_shadow(self, pylonsapp):
223 257 """
224 258 Check that the set_repo_names method sets all names to the one returned
225 259 by the _get_repository_name method on a request to a non shadow repo.
226 260 """
227 261 environ_stub = {}
228 262 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
229 263 controller._name = 'RepoGroup/MyRepo'
230 264 controller.set_repo_names(environ_stub)
231 265 assert not controller.is_shadow_repo
232 266 assert (controller.url_repo_name ==
233 267 controller.acl_repo_name ==
234 268 controller.vcs_repo_name ==
235 269 controller._get_repository_name(environ_stub))
236 270
237 271 def test_set_repo_names_with_shadow(self, pylonsapp, pr_util):
238 272 """
239 273 Check that the set_repo_names method sets correct names on a request
240 274 to a shadow repo.
241 275 """
242 276 from rhodecode.model.pull_request import PullRequestModel
243 277
244 278 pull_request = pr_util.create_pull_request()
245 279 shadow_url = '{target}/pull-request/{pr_id}/repository'.format(
246 280 target=pull_request.target_repo.repo_name,
247 281 pr_id=pull_request.pull_request_id)
248 282 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
249 283 controller._name = shadow_url
250 284 controller.set_repo_names({})
251 285
252 286 # Get file system path to shadow repo for assertions.
253 287 workspace_id = PullRequestModel()._workspace_id(pull_request)
254 288 target_vcs = pull_request.target_repo.scm_instance()
255 289 vcs_repo_name = target_vcs._get_shadow_repository_path(
256 290 workspace_id)
257 291
258 292 assert controller.vcs_repo_name == vcs_repo_name
259 293 assert controller.url_repo_name == shadow_url
260 294 assert controller.acl_repo_name == pull_request.target_repo.repo_name
261 295 assert controller.is_shadow_repo
262 296
263 297 def test_set_repo_names_with_shadow_but_missing_pr(
264 298 self, pylonsapp, pr_util):
265 299 """
266 300 Checks that the set_repo_names method enforces matching target repos
267 301 and pull request IDs.
268 302 """
269 303 pull_request = pr_util.create_pull_request()
270 304 shadow_url = '{target}/pull-request/{pr_id}/repository'.format(
271 305 target=pull_request.target_repo.repo_name,
272 306 pr_id=999999999)
273 307 controller = StubVCSController(pylonsapp, pylonsapp.config, None)
274 308 controller._name = shadow_url
275 309 controller.set_repo_names({})
276 310
277 311 assert not controller.is_shadow_repo
278 312 assert (controller.url_repo_name ==
279 313 controller.acl_repo_name ==
280 314 controller.vcs_repo_name)
281 315
282 316
283 317 @pytest.mark.usefixtures('db')
284 318 @mock.patch.multiple(
285 319 'Pyro4.config', SERVERTYPE='multiplex', POLLTIMEOUT=0.01)
286 320 class TestGenerateVcsResponse:
287 321
288 322 def test_ensures_that_start_response_is_called_early_enough(self):
289 323 self.call_controller_with_response_body(iter(['a', 'b']))
290 324 assert self.start_response.called
291 325
292 326 def test_invalidates_cache_after_body_is_consumed(self):
293 327 result = self.call_controller_with_response_body(iter(['a', 'b']))
294 328 assert not self.was_cache_invalidated()
295 329 # Consume the result
296 330 list(result)
297 331 assert self.was_cache_invalidated()
298 332
299 333 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
300 334 def test_handles_locking_exception(self, http_locked_rc):
301 335 result = self.call_controller_with_response_body(
302 336 self.raise_result_iter(vcs_kind='repo_locked'))
303 337 assert not http_locked_rc.called
304 338 # Consume the result
305 339 list(result)
306 340 assert http_locked_rc.called
307 341
308 342 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPRequirementError')
309 343 def test_handles_requirement_exception(self, http_requirement):
310 344 result = self.call_controller_with_response_body(
311 345 self.raise_result_iter(vcs_kind='requirement'))
312 346 assert not http_requirement.called
313 347 # Consume the result
314 348 list(result)
315 349 assert http_requirement.called
316 350
317 351 @mock.patch('rhodecode.lib.middleware.simplevcs.HTTPLockedRC')
318 352 def test_handles_locking_exception_in_app_call(self, http_locked_rc):
319 353 app_factory_patcher = mock.patch.object(
320 354 StubVCSController, '_create_wsgi_app')
321 355 with app_factory_patcher as app_factory:
322 356 app_factory().side_effect = self.vcs_exception()
323 357 result = self.call_controller_with_response_body(['a'])
324 358 list(result)
325 359 assert http_locked_rc.called
326 360
327 361 def test_raises_unknown_exceptions(self):
328 362 result = self.call_controller_with_response_body(
329 363 self.raise_result_iter(vcs_kind='unknown'))
330 364 with pytest.raises(Exception):
331 365 list(result)
332 366
333 367 def test_prepare_callback_daemon_is_called(self):
334 368 def side_effect(extras):
335 369 return DummyHooksCallbackDaemon(), extras
336 370
337 371 prepare_patcher = mock.patch.object(
338 372 StubVCSController, '_prepare_callback_daemon')
339 373 with prepare_patcher as prepare_mock:
340 374 prepare_mock.side_effect = side_effect
341 375 self.call_controller_with_response_body(iter(['a', 'b']))
342 376 assert prepare_mock.called
343 377 assert prepare_mock.call_count == 1
344 378
345 379 def call_controller_with_response_body(self, response_body):
346 380 settings = {
347 381 'base_path': 'fake_base_path',
348 382 'vcs.hooks.protocol': 'http',
349 383 'vcs.hooks.direct_calls': False,
350 384 }
351 385 controller = StubVCSController(None, settings, None)
352 386 controller._invalidate_cache = mock.Mock()
353 387 controller.stub_response_body = response_body
354 388 self.start_response = mock.Mock()
355 389 result = controller._generate_vcs_response(
356 390 environ={}, start_response=self.start_response,
357 391 repo_path='fake_repo_path',
358 392 extras={}, action='push')
359 393 self.controller = controller
360 394 return result
361 395
362 396 def raise_result_iter(self, vcs_kind='repo_locked'):
363 397 """
364 398 Simulates an exception due to a vcs raised exception if kind vcs_kind
365 399 """
366 400 raise self.vcs_exception(vcs_kind=vcs_kind)
367 401 yield "never_reached"
368 402
369 403 def vcs_exception(self, vcs_kind='repo_locked'):
370 404 locked_exception = Exception('TEST_MESSAGE')
371 405 locked_exception._vcs_kind = vcs_kind
372 406 return locked_exception
373 407
374 408 def was_cache_invalidated(self):
375 409 return self.controller._invalidate_cache.called
376 410
377 411
378 412 class TestInitializeGenerator:
379 413
380 414 def test_drains_first_element(self):
381 415 gen = self.factory(['__init__', 1, 2])
382 416 result = list(gen)
383 417 assert result == [1, 2]
384 418
385 419 @pytest.mark.parametrize('values', [
386 420 [],
387 421 [1, 2],
388 422 ])
389 423 def test_raises_value_error(self, values):
390 424 with pytest.raises(ValueError):
391 425 self.factory(values)
392 426
393 427 @simplevcs.initialize_generator
394 428 def factory(self, iterable):
395 429 for elem in iterable:
396 430 yield elem
397 431
398 432
399 433 class TestPrepareHooksDaemon(object):
400 434 def test_calls_imported_prepare_callback_daemon(self, app_settings):
401 435 expected_extras = {'extra1': 'value1'}
402 436 daemon = DummyHooksCallbackDaemon()
403 437
404 438 controller = StubVCSController(None, app_settings, None)
405 439 prepare_patcher = mock.patch.object(
406 440 simplevcs, 'prepare_callback_daemon',
407 441 return_value=(daemon, expected_extras))
408 442 with prepare_patcher as prepare_mock:
409 443 callback_daemon, extras = controller._prepare_callback_daemon(
410 444 expected_extras.copy())
411 445 prepare_mock.assert_called_once_with(
412 446 expected_extras,
413 447 protocol=app_settings['vcs.hooks.protocol'],
414 448 use_direct_calls=app_settings['vcs.hooks.direct_calls'])
415 449
416 450 assert callback_daemon == daemon
417 451 assert extras == extras
General Comments 0
You need to be logged in to leave comments. Login now