##// END OF EJS Templates
tests: small code cleanup
marcink -
r2315:a5a03d0b default
parent child Browse files
Show More
@@ -1,1858 +1,1855 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import collections
21 import collections
22 import datetime
22 import datetime
23 import hashlib
23 import hashlib
24 import os
24 import os
25 import re
25 import re
26 import pprint
26 import pprint
27 import shutil
27 import shutil
28 import socket
28 import socket
29 import subprocess32
29 import subprocess32
30 import time
30 import time
31 import uuid
31 import uuid
32 import dateutil.tz
32 import dateutil.tz
33
33
34 import mock
34 import mock
35 import pyramid.testing
35 import pyramid.testing
36 import pytest
36 import pytest
37 import colander
37 import colander
38 import requests
38 import requests
39
39
40 import rhodecode
40 import rhodecode
41 from rhodecode.lib.utils2 import AttributeDict
41 from rhodecode.lib.utils2 import AttributeDict
42 from rhodecode.model.changeset_status import ChangesetStatusModel
42 from rhodecode.model.changeset_status import ChangesetStatusModel
43 from rhodecode.model.comment import CommentsModel
43 from rhodecode.model.comment import CommentsModel
44 from rhodecode.model.db import (
44 from rhodecode.model.db import (
45 PullRequest, Repository, RhodeCodeSetting, ChangesetStatus, RepoGroup,
45 PullRequest, Repository, RhodeCodeSetting, ChangesetStatus, RepoGroup,
46 UserGroup, RepoRhodeCodeUi, RepoRhodeCodeSetting, RhodeCodeUi)
46 UserGroup, RepoRhodeCodeUi, RepoRhodeCodeSetting, RhodeCodeUi)
47 from rhodecode.model.meta import Session
47 from rhodecode.model.meta import Session
48 from rhodecode.model.pull_request import PullRequestModel
48 from rhodecode.model.pull_request import PullRequestModel
49 from rhodecode.model.repo import RepoModel
49 from rhodecode.model.repo import RepoModel
50 from rhodecode.model.repo_group import RepoGroupModel
50 from rhodecode.model.repo_group import RepoGroupModel
51 from rhodecode.model.user import UserModel
51 from rhodecode.model.user import UserModel
52 from rhodecode.model.settings import VcsSettingsModel
52 from rhodecode.model.settings import VcsSettingsModel
53 from rhodecode.model.user_group import UserGroupModel
53 from rhodecode.model.user_group import UserGroupModel
54 from rhodecode.model.integration import IntegrationModel
54 from rhodecode.model.integration import IntegrationModel
55 from rhodecode.integrations import integration_type_registry
55 from rhodecode.integrations import integration_type_registry
56 from rhodecode.integrations.types.base import IntegrationTypeBase
56 from rhodecode.integrations.types.base import IntegrationTypeBase
57 from rhodecode.lib.utils import repo2db_mapper
57 from rhodecode.lib.utils import repo2db_mapper
58 from rhodecode.lib.vcs import create_vcsserver_proxy
58 from rhodecode.lib.vcs import create_vcsserver_proxy
59 from rhodecode.lib.vcs.backends import get_backend
59 from rhodecode.lib.vcs.backends import get_backend
60 from rhodecode.lib.vcs.nodes import FileNode
60 from rhodecode.lib.vcs.nodes import FileNode
61 from rhodecode.tests import (
61 from rhodecode.tests import (
62 login_user_session, get_new_dir, utils, TESTS_TMP_PATH,
62 login_user_session, get_new_dir, utils, TESTS_TMP_PATH,
63 TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR2_LOGIN,
63 TEST_USER_ADMIN_LOGIN, TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR2_LOGIN,
64 TEST_USER_REGULAR_PASS)
64 TEST_USER_REGULAR_PASS)
65 from rhodecode.tests.utils import CustomTestApp, set_anonymous_access
65 from rhodecode.tests.utils import CustomTestApp, set_anonymous_access
66 from rhodecode.tests.fixture import Fixture
66 from rhodecode.tests.fixture import Fixture
67
67
68
68
69 def _split_comma(value):
69 def _split_comma(value):
70 return value.split(',')
70 return value.split(',')
71
71
72
72
73 def pytest_addoption(parser):
73 def pytest_addoption(parser):
74 parser.addoption(
74 parser.addoption(
75 '--keep-tmp-path', action='store_true',
75 '--keep-tmp-path', action='store_true',
76 help="Keep the test temporary directories")
76 help="Keep the test temporary directories")
77 parser.addoption(
77 parser.addoption(
78 '--backends', action='store', type=_split_comma,
78 '--backends', action='store', type=_split_comma,
79 default=['git', 'hg', 'svn'],
79 default=['git', 'hg', 'svn'],
80 help="Select which backends to test for backend specific tests.")
80 help="Select which backends to test for backend specific tests.")
81 parser.addoption(
81 parser.addoption(
82 '--dbs', action='store', type=_split_comma,
82 '--dbs', action='store', type=_split_comma,
83 default=['sqlite'],
83 default=['sqlite'],
84 help="Select which database to test for database specific tests. "
84 help="Select which database to test for database specific tests. "
85 "Possible options are sqlite,postgres,mysql")
85 "Possible options are sqlite,postgres,mysql")
86 parser.addoption(
86 parser.addoption(
87 '--appenlight', '--ae', action='store_true',
87 '--appenlight', '--ae', action='store_true',
88 help="Track statistics in appenlight.")
88 help="Track statistics in appenlight.")
89 parser.addoption(
89 parser.addoption(
90 '--appenlight-api-key', '--ae-key',
90 '--appenlight-api-key', '--ae-key',
91 help="API key for Appenlight.")
91 help="API key for Appenlight.")
92 parser.addoption(
92 parser.addoption(
93 '--appenlight-url', '--ae-url',
93 '--appenlight-url', '--ae-url',
94 default="https://ae.rhodecode.com",
94 default="https://ae.rhodecode.com",
95 help="Appenlight service URL, defaults to https://ae.rhodecode.com")
95 help="Appenlight service URL, defaults to https://ae.rhodecode.com")
96 parser.addoption(
96 parser.addoption(
97 '--sqlite-connection-string', action='store',
97 '--sqlite-connection-string', action='store',
98 default='', help="Connection string for the dbs tests with SQLite")
98 default='', help="Connection string for the dbs tests with SQLite")
99 parser.addoption(
99 parser.addoption(
100 '--postgres-connection-string', action='store',
100 '--postgres-connection-string', action='store',
101 default='', help="Connection string for the dbs tests with Postgres")
101 default='', help="Connection string for the dbs tests with Postgres")
102 parser.addoption(
102 parser.addoption(
103 '--mysql-connection-string', action='store',
103 '--mysql-connection-string', action='store',
104 default='', help="Connection string for the dbs tests with MySQL")
104 default='', help="Connection string for the dbs tests with MySQL")
105 parser.addoption(
105 parser.addoption(
106 '--repeat', type=int, default=100,
106 '--repeat', type=int, default=100,
107 help="Number of repetitions in performance tests.")
107 help="Number of repetitions in performance tests.")
108
108
109
109
110 def pytest_configure(config):
110 def pytest_configure(config):
111 # Appy the kombu patch early on, needed for test discovery on Python 2.7.11
111 # Appy the kombu patch early on, needed for test discovery on Python 2.7.11
112 from rhodecode.config import patches
112 from rhodecode.config import patches
113 patches.kombu_1_5_1_python_2_7_11()
113 patches.kombu_1_5_1_python_2_7_11()
114
114
115
115
116 def pytest_collection_modifyitems(session, config, items):
116 def pytest_collection_modifyitems(session, config, items):
117 # nottest marked, compare nose, used for transition from nose to pytest
117 # nottest marked, compare nose, used for transition from nose to pytest
118 remaining = [
118 remaining = [
119 i for i in items if getattr(i.obj, '__test__', True)]
119 i for i in items if getattr(i.obj, '__test__', True)]
120 items[:] = remaining
120 items[:] = remaining
121
121
122
122
123 def pytest_generate_tests(metafunc):
123 def pytest_generate_tests(metafunc):
124 # Support test generation based on --backend parameter
124 # Support test generation based on --backend parameter
125 if 'backend_alias' in metafunc.fixturenames:
125 if 'backend_alias' in metafunc.fixturenames:
126 backends = get_backends_from_metafunc(metafunc)
126 backends = get_backends_from_metafunc(metafunc)
127 scope = None
127 scope = None
128 if not backends:
128 if not backends:
129 pytest.skip("Not enabled for any of selected backends")
129 pytest.skip("Not enabled for any of selected backends")
130 metafunc.parametrize('backend_alias', backends, scope=scope)
130 metafunc.parametrize('backend_alias', backends, scope=scope)
131 elif hasattr(metafunc.function, 'backends'):
131 elif hasattr(metafunc.function, 'backends'):
132 backends = get_backends_from_metafunc(metafunc)
132 backends = get_backends_from_metafunc(metafunc)
133 if not backends:
133 if not backends:
134 pytest.skip("Not enabled for any of selected backends")
134 pytest.skip("Not enabled for any of selected backends")
135
135
136
136
137 def get_backends_from_metafunc(metafunc):
137 def get_backends_from_metafunc(metafunc):
138 requested_backends = set(metafunc.config.getoption('--backends'))
138 requested_backends = set(metafunc.config.getoption('--backends'))
139 if hasattr(metafunc.function, 'backends'):
139 if hasattr(metafunc.function, 'backends'):
140 # Supported backends by this test function, created from
140 # Supported backends by this test function, created from
141 # pytest.mark.backends
141 # pytest.mark.backends
142 backends = metafunc.function.backends.args
142 backends = metafunc.function.backends.args
143 elif hasattr(metafunc.cls, 'backend_alias'):
143 elif hasattr(metafunc.cls, 'backend_alias'):
144 # Support class attribute "backend_alias", this is mainly
144 # Support class attribute "backend_alias", this is mainly
145 # for legacy reasons for tests not yet using pytest.mark.backends
145 # for legacy reasons for tests not yet using pytest.mark.backends
146 backends = [metafunc.cls.backend_alias]
146 backends = [metafunc.cls.backend_alias]
147 else:
147 else:
148 backends = metafunc.config.getoption('--backends')
148 backends = metafunc.config.getoption('--backends')
149 return requested_backends.intersection(backends)
149 return requested_backends.intersection(backends)
150
150
151
151
152 @pytest.fixture(scope='session', autouse=True)
152 @pytest.fixture(scope='session', autouse=True)
153 def activate_example_rcextensions(request):
153 def activate_example_rcextensions(request):
154 """
154 """
155 Patch in an example rcextensions module which verifies passed in kwargs.
155 Patch in an example rcextensions module which verifies passed in kwargs.
156 """
156 """
157 from rhodecode.tests.other import example_rcextensions
157 from rhodecode.tests.other import example_rcextensions
158
158
159 old_extensions = rhodecode.EXTENSIONS
159 old_extensions = rhodecode.EXTENSIONS
160 rhodecode.EXTENSIONS = example_rcextensions
160 rhodecode.EXTENSIONS = example_rcextensions
161
161
162 @request.addfinalizer
162 @request.addfinalizer
163 def cleanup():
163 def cleanup():
164 rhodecode.EXTENSIONS = old_extensions
164 rhodecode.EXTENSIONS = old_extensions
165
165
166
166
167 @pytest.fixture
167 @pytest.fixture
168 def capture_rcextensions():
168 def capture_rcextensions():
169 """
169 """
170 Returns the recorded calls to entry points in rcextensions.
170 Returns the recorded calls to entry points in rcextensions.
171 """
171 """
172 calls = rhodecode.EXTENSIONS.calls
172 calls = rhodecode.EXTENSIONS.calls
173 calls.clear()
173 calls.clear()
174 # Note: At this moment, it is still the empty dict, but that will
174 # Note: At this moment, it is still the empty dict, but that will
175 # be filled during the test run and since it is a reference this
175 # be filled during the test run and since it is a reference this
176 # is enough to make it work.
176 # is enough to make it work.
177 return calls
177 return calls
178
178
179
179
180 @pytest.fixture(scope='session')
180 @pytest.fixture(scope='session')
181 def http_environ_session():
181 def http_environ_session():
182 """
182 """
183 Allow to use "http_environ" in session scope.
183 Allow to use "http_environ" in session scope.
184 """
184 """
185 return http_environ(
185 return http_environ(
186 http_host_stub=http_host_stub())
186 http_host_stub=http_host_stub())
187
187
188
188
189 @pytest.fixture
189 @pytest.fixture
190 def http_host_stub():
190 def http_host_stub():
191 """
191 """
192 Value of HTTP_HOST in the test run.
192 Value of HTTP_HOST in the test run.
193 """
193 """
194 return 'example.com:80'
194 return 'example.com:80'
195
195
196
196
197 @pytest.fixture
197 @pytest.fixture
198 def http_host_only_stub():
198 def http_host_only_stub():
199 """
199 """
200 Value of HTTP_HOST in the test run.
200 Value of HTTP_HOST in the test run.
201 """
201 """
202 return http_host_stub().split(':')[0]
202 return http_host_stub().split(':')[0]
203
203
204
204
205 @pytest.fixture
205 @pytest.fixture
206 def http_environ(http_host_stub):
206 def http_environ(http_host_stub):
207 """
207 """
208 HTTP extra environ keys.
208 HTTP extra environ keys.
209
209
210 User by the test application and as well for setting up the pylons
210 User by the test application and as well for setting up the pylons
211 environment. In the case of the fixture "app" it should be possible
211 environment. In the case of the fixture "app" it should be possible
212 to override this for a specific test case.
212 to override this for a specific test case.
213 """
213 """
214 return {
214 return {
215 'SERVER_NAME': http_host_only_stub(),
215 'SERVER_NAME': http_host_only_stub(),
216 'SERVER_PORT': http_host_stub.split(':')[1],
216 'SERVER_PORT': http_host_stub.split(':')[1],
217 'HTTP_HOST': http_host_stub,
217 'HTTP_HOST': http_host_stub,
218 'HTTP_USER_AGENT': 'rc-test-agent',
218 'HTTP_USER_AGENT': 'rc-test-agent',
219 'REQUEST_METHOD': 'GET'
219 'REQUEST_METHOD': 'GET'
220 }
220 }
221
221
222
222
223 @pytest.fixture(scope='function')
223 @pytest.fixture(scope='function')
224 def app(request, config_stub, pylonsapp, http_environ):
224 def app(request, config_stub, pylonsapp, http_environ):
225 app = CustomTestApp(
225 app = CustomTestApp(
226 pylonsapp,
226 pylonsapp,
227 extra_environ=http_environ)
227 extra_environ=http_environ)
228 if request.cls:
228 if request.cls:
229 request.cls.app = app
229 request.cls.app = app
230 return app
230 return app
231
231
232
232
233 @pytest.fixture(scope='session')
233 @pytest.fixture(scope='session')
234 def app_settings(pylonsapp, pylons_config):
234 def app_settings(pylonsapp, pylons_config):
235 """
235 """
236 Settings dictionary used to create the app.
236 Settings dictionary used to create the app.
237
237
238 Parses the ini file and passes the result through the sanitize and apply
238 Parses the ini file and passes the result through the sanitize and apply
239 defaults mechanism in `rhodecode.config.middleware`.
239 defaults mechanism in `rhodecode.config.middleware`.
240 """
240 """
241 from paste.deploy.loadwsgi import loadcontext, APP
241 from paste.deploy.loadwsgi import loadcontext, APP
242 from rhodecode.config.middleware import (
242 from rhodecode.config.middleware import (
243 sanitize_settings_and_apply_defaults)
243 sanitize_settings_and_apply_defaults)
244 context = loadcontext(APP, 'config:' + pylons_config)
244 context = loadcontext(APP, 'config:' + pylons_config)
245 settings = sanitize_settings_and_apply_defaults(context.config())
245 settings = sanitize_settings_and_apply_defaults(context.config())
246 return settings
246 return settings
247
247
248
248
249 @pytest.fixture(scope='session')
249 @pytest.fixture(scope='session')
250 def db(app_settings):
250 def db(app_settings):
251 """
251 """
252 Initializes the database connection.
252 Initializes the database connection.
253
253
254 It uses the same settings which are used to create the ``pylonsapp`` or
254 It uses the same settings which are used to create the ``pylonsapp`` or
255 ``app`` fixtures.
255 ``app`` fixtures.
256 """
256 """
257 from rhodecode.config.utils import initialize_database
257 from rhodecode.config.utils import initialize_database
258 initialize_database(app_settings)
258 initialize_database(app_settings)
259
259
260
260
261 LoginData = collections.namedtuple('LoginData', ('csrf_token', 'user'))
261 LoginData = collections.namedtuple('LoginData', ('csrf_token', 'user'))
262
262
263
263
264 def _autologin_user(app, *args):
264 def _autologin_user(app, *args):
265 session = login_user_session(app, *args)
265 session = login_user_session(app, *args)
266 csrf_token = rhodecode.lib.auth.get_csrf_token(session)
266 csrf_token = rhodecode.lib.auth.get_csrf_token(session)
267 return LoginData(csrf_token, session['rhodecode_user'])
267 return LoginData(csrf_token, session['rhodecode_user'])
268
268
269
269
270 @pytest.fixture
270 @pytest.fixture
271 def autologin_user(app):
271 def autologin_user(app):
272 """
272 """
273 Utility fixture which makes sure that the admin user is logged in
273 Utility fixture which makes sure that the admin user is logged in
274 """
274 """
275 return _autologin_user(app)
275 return _autologin_user(app)
276
276
277
277
278 @pytest.fixture
278 @pytest.fixture
279 def autologin_regular_user(app):
279 def autologin_regular_user(app):
280 """
280 """
281 Utility fixture which makes sure that the regular user is logged in
281 Utility fixture which makes sure that the regular user is logged in
282 """
282 """
283 return _autologin_user(
283 return _autologin_user(
284 app, TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS)
284 app, TEST_USER_REGULAR_LOGIN, TEST_USER_REGULAR_PASS)
285
285
286
286
287 @pytest.fixture(scope='function')
287 @pytest.fixture(scope='function')
288 def csrf_token(request, autologin_user):
288 def csrf_token(request, autologin_user):
289 return autologin_user.csrf_token
289 return autologin_user.csrf_token
290
290
291
291
292 @pytest.fixture(scope='function')
292 @pytest.fixture(scope='function')
293 def xhr_header(request):
293 def xhr_header(request):
294 return {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
294 return {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
295
295
296
296
297 @pytest.fixture
297 @pytest.fixture
298 def real_crypto_backend(monkeypatch):
298 def real_crypto_backend(monkeypatch):
299 """
299 """
300 Switch the production crypto backend on for this test.
300 Switch the production crypto backend on for this test.
301
301
302 During the test run the crypto backend is replaced with a faster
302 During the test run the crypto backend is replaced with a faster
303 implementation based on the MD5 algorithm.
303 implementation based on the MD5 algorithm.
304 """
304 """
305 monkeypatch.setattr(rhodecode, 'is_test', False)
305 monkeypatch.setattr(rhodecode, 'is_test', False)
306
306
307
307
308 @pytest.fixture(scope='class')
308 @pytest.fixture(scope='class')
309 def index_location(request, pylonsapp):
309 def index_location(request, pylonsapp):
310 index_location = pylonsapp.config['app_conf']['search.location']
310 index_location = pylonsapp.config['app_conf']['search.location']
311 if request.cls:
311 if request.cls:
312 request.cls.index_location = index_location
312 request.cls.index_location = index_location
313 return index_location
313 return index_location
314
314
315
315
316 @pytest.fixture(scope='session', autouse=True)
316 @pytest.fixture(scope='session', autouse=True)
317 def tests_tmp_path(request):
317 def tests_tmp_path(request):
318 """
318 """
319 Create temporary directory to be used during the test session.
319 Create temporary directory to be used during the test session.
320 """
320 """
321 if not os.path.exists(TESTS_TMP_PATH):
321 if not os.path.exists(TESTS_TMP_PATH):
322 os.makedirs(TESTS_TMP_PATH)
322 os.makedirs(TESTS_TMP_PATH)
323
323
324 if not request.config.getoption('--keep-tmp-path'):
324 if not request.config.getoption('--keep-tmp-path'):
325 @request.addfinalizer
325 @request.addfinalizer
326 def remove_tmp_path():
326 def remove_tmp_path():
327 shutil.rmtree(TESTS_TMP_PATH)
327 shutil.rmtree(TESTS_TMP_PATH)
328
328
329 return TESTS_TMP_PATH
329 return TESTS_TMP_PATH
330
330
331
331
332 @pytest.fixture
332 @pytest.fixture
333 def test_repo_group(request):
333 def test_repo_group(request):
334 """
334 """
335 Create a temporary repository group, and destroy it after
335 Create a temporary repository group, and destroy it after
336 usage automatically
336 usage automatically
337 """
337 """
338 fixture = Fixture()
338 fixture = Fixture()
339 repogroupid = 'test_repo_group_%s' % str(time.time()).replace('.', '')
339 repogroupid = 'test_repo_group_%s' % str(time.time()).replace('.', '')
340 repo_group = fixture.create_repo_group(repogroupid)
340 repo_group = fixture.create_repo_group(repogroupid)
341
341
342 def _cleanup():
342 def _cleanup():
343 fixture.destroy_repo_group(repogroupid)
343 fixture.destroy_repo_group(repogroupid)
344
344
345 request.addfinalizer(_cleanup)
345 request.addfinalizer(_cleanup)
346 return repo_group
346 return repo_group
347
347
348
348
349 @pytest.fixture
349 @pytest.fixture
350 def test_user_group(request):
350 def test_user_group(request):
351 """
351 """
352 Create a temporary user group, and destroy it after
352 Create a temporary user group, and destroy it after
353 usage automatically
353 usage automatically
354 """
354 """
355 fixture = Fixture()
355 fixture = Fixture()
356 usergroupid = 'test_user_group_%s' % str(time.time()).replace('.', '')
356 usergroupid = 'test_user_group_%s' % str(time.time()).replace('.', '')
357 user_group = fixture.create_user_group(usergroupid)
357 user_group = fixture.create_user_group(usergroupid)
358
358
359 def _cleanup():
359 def _cleanup():
360 fixture.destroy_user_group(user_group)
360 fixture.destroy_user_group(user_group)
361
361
362 request.addfinalizer(_cleanup)
362 request.addfinalizer(_cleanup)
363 return user_group
363 return user_group
364
364
365
365
366 @pytest.fixture(scope='session')
366 @pytest.fixture(scope='session')
367 def test_repo(request):
367 def test_repo(request):
368 container = TestRepoContainer()
368 container = TestRepoContainer()
369 request.addfinalizer(container._cleanup)
369 request.addfinalizer(container._cleanup)
370 return container
370 return container
371
371
372
372
373 class TestRepoContainer(object):
373 class TestRepoContainer(object):
374 """
374 """
375 Container for test repositories which are used read only.
375 Container for test repositories which are used read only.
376
376
377 Repositories will be created on demand and re-used during the lifetime
377 Repositories will be created on demand and re-used during the lifetime
378 of this object.
378 of this object.
379
379
380 Usage to get the svn test repository "minimal"::
380 Usage to get the svn test repository "minimal"::
381
381
382 test_repo = TestContainer()
382 test_repo = TestContainer()
383 repo = test_repo('minimal', 'svn')
383 repo = test_repo('minimal', 'svn')
384
384
385 """
385 """
386
386
387 dump_extractors = {
387 dump_extractors = {
388 'git': utils.extract_git_repo_from_dump,
388 'git': utils.extract_git_repo_from_dump,
389 'hg': utils.extract_hg_repo_from_dump,
389 'hg': utils.extract_hg_repo_from_dump,
390 'svn': utils.extract_svn_repo_from_dump,
390 'svn': utils.extract_svn_repo_from_dump,
391 }
391 }
392
392
393 def __init__(self):
393 def __init__(self):
394 self._cleanup_repos = []
394 self._cleanup_repos = []
395 self._fixture = Fixture()
395 self._fixture = Fixture()
396 self._repos = {}
396 self._repos = {}
397
397
398 def __call__(self, dump_name, backend_alias, config=None):
398 def __call__(self, dump_name, backend_alias, config=None):
399 key = (dump_name, backend_alias)
399 key = (dump_name, backend_alias)
400 if key not in self._repos:
400 if key not in self._repos:
401 repo = self._create_repo(dump_name, backend_alias, config)
401 repo = self._create_repo(dump_name, backend_alias, config)
402 self._repos[key] = repo.repo_id
402 self._repos[key] = repo.repo_id
403 return Repository.get(self._repos[key])
403 return Repository.get(self._repos[key])
404
404
405 def _create_repo(self, dump_name, backend_alias, config):
405 def _create_repo(self, dump_name, backend_alias, config):
406 repo_name = '%s-%s' % (backend_alias, dump_name)
406 repo_name = '%s-%s' % (backend_alias, dump_name)
407 backend_class = get_backend(backend_alias)
407 backend_class = get_backend(backend_alias)
408 dump_extractor = self.dump_extractors[backend_alias]
408 dump_extractor = self.dump_extractors[backend_alias]
409 repo_path = dump_extractor(dump_name, repo_name)
409 repo_path = dump_extractor(dump_name, repo_name)
410
410
411 vcs_repo = backend_class(repo_path, config=config)
411 vcs_repo = backend_class(repo_path, config=config)
412 repo2db_mapper({repo_name: vcs_repo})
412 repo2db_mapper({repo_name: vcs_repo})
413
413
414 repo = RepoModel().get_by_repo_name(repo_name)
414 repo = RepoModel().get_by_repo_name(repo_name)
415 self._cleanup_repos.append(repo_name)
415 self._cleanup_repos.append(repo_name)
416 return repo
416 return repo
417
417
418 def _cleanup(self):
418 def _cleanup(self):
419 for repo_name in reversed(self._cleanup_repos):
419 for repo_name in reversed(self._cleanup_repos):
420 self._fixture.destroy_repo(repo_name)
420 self._fixture.destroy_repo(repo_name)
421
421
422
422
423 @pytest.fixture
423 @pytest.fixture
424 def backend(request, backend_alias, pylonsapp, test_repo):
424 def backend(request, backend_alias, pylonsapp, test_repo):
425 """
425 """
426 Parametrized fixture which represents a single backend implementation.
426 Parametrized fixture which represents a single backend implementation.
427
427
428 It respects the option `--backends` to focus the test run on specific
428 It respects the option `--backends` to focus the test run on specific
429 backend implementations.
429 backend implementations.
430
430
431 It also supports `pytest.mark.xfail_backends` to mark tests as failing
431 It also supports `pytest.mark.xfail_backends` to mark tests as failing
432 for specific backends. This is intended as a utility for incremental
432 for specific backends. This is intended as a utility for incremental
433 development of a new backend implementation.
433 development of a new backend implementation.
434 """
434 """
435 if backend_alias not in request.config.getoption('--backends'):
435 if backend_alias not in request.config.getoption('--backends'):
436 pytest.skip("Backend %s not selected." % (backend_alias, ))
436 pytest.skip("Backend %s not selected." % (backend_alias, ))
437
437
438 utils.check_xfail_backends(request.node, backend_alias)
438 utils.check_xfail_backends(request.node, backend_alias)
439 utils.check_skip_backends(request.node, backend_alias)
439 utils.check_skip_backends(request.node, backend_alias)
440
440
441 repo_name = 'vcs_test_%s' % (backend_alias, )
441 repo_name = 'vcs_test_%s' % (backend_alias, )
442 backend = Backend(
442 backend = Backend(
443 alias=backend_alias,
443 alias=backend_alias,
444 repo_name=repo_name,
444 repo_name=repo_name,
445 test_name=request.node.name,
445 test_name=request.node.name,
446 test_repo_container=test_repo)
446 test_repo_container=test_repo)
447 request.addfinalizer(backend.cleanup)
447 request.addfinalizer(backend.cleanup)
448 return backend
448 return backend
449
449
450
450
451 @pytest.fixture
451 @pytest.fixture
452 def backend_git(request, pylonsapp, test_repo):
452 def backend_git(request, pylonsapp, test_repo):
453 return backend(request, 'git', pylonsapp, test_repo)
453 return backend(request, 'git', pylonsapp, test_repo)
454
454
455
455
456 @pytest.fixture
456 @pytest.fixture
457 def backend_hg(request, pylonsapp, test_repo):
457 def backend_hg(request, pylonsapp, test_repo):
458 return backend(request, 'hg', pylonsapp, test_repo)
458 return backend(request, 'hg', pylonsapp, test_repo)
459
459
460
460
461 @pytest.fixture
461 @pytest.fixture
462 def backend_svn(request, pylonsapp, test_repo):
462 def backend_svn(request, pylonsapp, test_repo):
463 return backend(request, 'svn', pylonsapp, test_repo)
463 return backend(request, 'svn', pylonsapp, test_repo)
464
464
465
465
466 @pytest.fixture
466 @pytest.fixture
467 def backend_random(backend_git):
467 def backend_random(backend_git):
468 """
468 """
469 Use this to express that your tests need "a backend.
469 Use this to express that your tests need "a backend.
470
470
471 A few of our tests need a backend, so that we can run the code. This
471 A few of our tests need a backend, so that we can run the code. This
472 fixture is intended to be used for such cases. It will pick one of the
472 fixture is intended to be used for such cases. It will pick one of the
473 backends and run the tests.
473 backends and run the tests.
474
474
475 The fixture `backend` would run the test multiple times for each
475 The fixture `backend` would run the test multiple times for each
476 available backend which is a pure waste of time if the test is
476 available backend which is a pure waste of time if the test is
477 independent of the backend type.
477 independent of the backend type.
478 """
478 """
479 # TODO: johbo: Change this to pick a random backend
479 # TODO: johbo: Change this to pick a random backend
480 return backend_git
480 return backend_git
481
481
482
482
483 @pytest.fixture
483 @pytest.fixture
484 def backend_stub(backend_git):
484 def backend_stub(backend_git):
485 """
485 """
486 Use this to express that your tests need a backend stub
486 Use this to express that your tests need a backend stub
487
487
488 TODO: mikhail: Implement a real stub logic instead of returning
488 TODO: mikhail: Implement a real stub logic instead of returning
489 a git backend
489 a git backend
490 """
490 """
491 return backend_git
491 return backend_git
492
492
493
493
494 @pytest.fixture
494 @pytest.fixture
495 def repo_stub(backend_stub):
495 def repo_stub(backend_stub):
496 """
496 """
497 Use this to express that your tests need a repository stub
497 Use this to express that your tests need a repository stub
498 """
498 """
499 return backend_stub.create_repo()
499 return backend_stub.create_repo()
500
500
501
501
502 class Backend(object):
502 class Backend(object):
503 """
503 """
504 Represents the test configuration for one supported backend
504 Represents the test configuration for one supported backend
505
505
506 Provides easy access to different test repositories based on
506 Provides easy access to different test repositories based on
507 `__getitem__`. Such repositories will only be created once per test
507 `__getitem__`. Such repositories will only be created once per test
508 session.
508 session.
509 """
509 """
510
510
511 invalid_repo_name = re.compile(r'[^0-9a-zA-Z]+')
511 invalid_repo_name = re.compile(r'[^0-9a-zA-Z]+')
512 _master_repo = None
512 _master_repo = None
513 _commit_ids = {}
513 _commit_ids = {}
514
514
515 def __init__(self, alias, repo_name, test_name, test_repo_container):
515 def __init__(self, alias, repo_name, test_name, test_repo_container):
516 self.alias = alias
516 self.alias = alias
517 self.repo_name = repo_name
517 self.repo_name = repo_name
518 self._cleanup_repos = []
518 self._cleanup_repos = []
519 self._test_name = test_name
519 self._test_name = test_name
520 self._test_repo_container = test_repo_container
520 self._test_repo_container = test_repo_container
521 # TODO: johbo: Used as a delegate interim. Not yet sure if Backend or
521 # TODO: johbo: Used as a delegate interim. Not yet sure if Backend or
522 # Fixture will survive in the end.
522 # Fixture will survive in the end.
523 self._fixture = Fixture()
523 self._fixture = Fixture()
524
524
525 def __getitem__(self, key):
525 def __getitem__(self, key):
526 return self._test_repo_container(key, self.alias)
526 return self._test_repo_container(key, self.alias)
527
527
528 def create_test_repo(self, key, config=None):
528 def create_test_repo(self, key, config=None):
529 return self._test_repo_container(key, self.alias, config)
529 return self._test_repo_container(key, self.alias, config)
530
530
531 @property
531 @property
532 def repo(self):
532 def repo(self):
533 """
533 """
534 Returns the "current" repository. This is the vcs_test repo or the
534 Returns the "current" repository. This is the vcs_test repo or the
535 last repo which has been created with `create_repo`.
535 last repo which has been created with `create_repo`.
536 """
536 """
537 from rhodecode.model.db import Repository
537 from rhodecode.model.db import Repository
538 return Repository.get_by_repo_name(self.repo_name)
538 return Repository.get_by_repo_name(self.repo_name)
539
539
540 @property
540 @property
541 def default_branch_name(self):
541 def default_branch_name(self):
542 VcsRepository = get_backend(self.alias)
542 VcsRepository = get_backend(self.alias)
543 return VcsRepository.DEFAULT_BRANCH_NAME
543 return VcsRepository.DEFAULT_BRANCH_NAME
544
544
545 @property
545 @property
546 def default_head_id(self):
546 def default_head_id(self):
547 """
547 """
548 Returns the default head id of the underlying backend.
548 Returns the default head id of the underlying backend.
549
549
550 This will be the default branch name in case the backend does have a
550 This will be the default branch name in case the backend does have a
551 default branch. In the other cases it will point to a valid head
551 default branch. In the other cases it will point to a valid head
552 which can serve as the base to create a new commit on top of it.
552 which can serve as the base to create a new commit on top of it.
553 """
553 """
554 vcsrepo = self.repo.scm_instance()
554 vcsrepo = self.repo.scm_instance()
555 head_id = (
555 head_id = (
556 vcsrepo.DEFAULT_BRANCH_NAME or
556 vcsrepo.DEFAULT_BRANCH_NAME or
557 vcsrepo.commit_ids[-1])
557 vcsrepo.commit_ids[-1])
558 return head_id
558 return head_id
559
559
560 @property
560 @property
561 def commit_ids(self):
561 def commit_ids(self):
562 """
562 """
563 Returns the list of commits for the last created repository
563 Returns the list of commits for the last created repository
564 """
564 """
565 return self._commit_ids
565 return self._commit_ids
566
566
567 def create_master_repo(self, commits):
567 def create_master_repo(self, commits):
568 """
568 """
569 Create a repository and remember it as a template.
569 Create a repository and remember it as a template.
570
570
571 This allows to easily create derived repositories to construct
571 This allows to easily create derived repositories to construct
572 more complex scenarios for diff, compare and pull requests.
572 more complex scenarios for diff, compare and pull requests.
573
573
574 Returns a commit map which maps from commit message to raw_id.
574 Returns a commit map which maps from commit message to raw_id.
575 """
575 """
576 self._master_repo = self.create_repo(commits=commits)
576 self._master_repo = self.create_repo(commits=commits)
577 return self._commit_ids
577 return self._commit_ids
578
578
579 def create_repo(
579 def create_repo(
580 self, commits=None, number_of_commits=0, heads=None,
580 self, commits=None, number_of_commits=0, heads=None,
581 name_suffix=u'', **kwargs):
581 name_suffix=u'', **kwargs):
582 """
582 """
583 Create a repository and record it for later cleanup.
583 Create a repository and record it for later cleanup.
584
584
585 :param commits: Optional. A sequence of dict instances.
585 :param commits: Optional. A sequence of dict instances.
586 Will add a commit per entry to the new repository.
586 Will add a commit per entry to the new repository.
587 :param number_of_commits: Optional. If set to a number, this number of
587 :param number_of_commits: Optional. If set to a number, this number of
588 commits will be added to the new repository.
588 commits will be added to the new repository.
589 :param heads: Optional. Can be set to a sequence of of commit
589 :param heads: Optional. Can be set to a sequence of of commit
590 names which shall be pulled in from the master repository.
590 names which shall be pulled in from the master repository.
591
591
592 """
592 """
593 self.repo_name = self._next_repo_name() + name_suffix
593 self.repo_name = self._next_repo_name() + name_suffix
594 repo = self._fixture.create_repo(
594 repo = self._fixture.create_repo(
595 self.repo_name, repo_type=self.alias, **kwargs)
595 self.repo_name, repo_type=self.alias, **kwargs)
596 self._cleanup_repos.append(repo.repo_name)
596 self._cleanup_repos.append(repo.repo_name)
597
597
598 commits = commits or [
598 commits = commits or [
599 {'message': 'Commit %s of %s' % (x, self.repo_name)}
599 {'message': 'Commit %s of %s' % (x, self.repo_name)}
600 for x in xrange(number_of_commits)]
600 for x in xrange(number_of_commits)]
601 self._add_commits_to_repo(repo.scm_instance(), commits)
601 self._add_commits_to_repo(repo.scm_instance(), commits)
602 if heads:
602 if heads:
603 self.pull_heads(repo, heads)
603 self.pull_heads(repo, heads)
604
604
605 return repo
605 return repo
606
606
607 def pull_heads(self, repo, heads):
607 def pull_heads(self, repo, heads):
608 """
608 """
609 Make sure that repo contains all commits mentioned in `heads`
609 Make sure that repo contains all commits mentioned in `heads`
610 """
610 """
611 vcsmaster = self._master_repo.scm_instance()
611 vcsmaster = self._master_repo.scm_instance()
612 vcsrepo = repo.scm_instance()
612 vcsrepo = repo.scm_instance()
613 vcsrepo.config.clear_section('hooks')
613 vcsrepo.config.clear_section('hooks')
614 commit_ids = [self._commit_ids[h] for h in heads]
614 commit_ids = [self._commit_ids[h] for h in heads]
615 vcsrepo.pull(vcsmaster.path, commit_ids=commit_ids)
615 vcsrepo.pull(vcsmaster.path, commit_ids=commit_ids)
616
616
617 def create_fork(self):
617 def create_fork(self):
618 repo_to_fork = self.repo_name
618 repo_to_fork = self.repo_name
619 self.repo_name = self._next_repo_name()
619 self.repo_name = self._next_repo_name()
620 repo = self._fixture.create_fork(repo_to_fork, self.repo_name)
620 repo = self._fixture.create_fork(repo_to_fork, self.repo_name)
621 self._cleanup_repos.append(self.repo_name)
621 self._cleanup_repos.append(self.repo_name)
622 return repo
622 return repo
623
623
624 def new_repo_name(self, suffix=u''):
624 def new_repo_name(self, suffix=u''):
625 self.repo_name = self._next_repo_name() + suffix
625 self.repo_name = self._next_repo_name() + suffix
626 self._cleanup_repos.append(self.repo_name)
626 self._cleanup_repos.append(self.repo_name)
627 return self.repo_name
627 return self.repo_name
628
628
629 def _next_repo_name(self):
629 def _next_repo_name(self):
630 return u"%s_%s" % (
630 return u"%s_%s" % (
631 self.invalid_repo_name.sub(u'_', self._test_name),
631 self.invalid_repo_name.sub(u'_', self._test_name),
632 len(self._cleanup_repos))
632 len(self._cleanup_repos))
633
633
634 def ensure_file(self, filename, content='Test content\n'):
634 def ensure_file(self, filename, content='Test content\n'):
635 assert self._cleanup_repos, "Avoid writing into vcs_test repos"
635 assert self._cleanup_repos, "Avoid writing into vcs_test repos"
636 commits = [
636 commits = [
637 {'added': [
637 {'added': [
638 FileNode(filename, content=content),
638 FileNode(filename, content=content),
639 ]},
639 ]},
640 ]
640 ]
641 self._add_commits_to_repo(self.repo.scm_instance(), commits)
641 self._add_commits_to_repo(self.repo.scm_instance(), commits)
642
642
643 def enable_downloads(self):
643 def enable_downloads(self):
644 repo = self.repo
644 repo = self.repo
645 repo.enable_downloads = True
645 repo.enable_downloads = True
646 Session().add(repo)
646 Session().add(repo)
647 Session().commit()
647 Session().commit()
648
648
649 def cleanup(self):
649 def cleanup(self):
650 for repo_name in reversed(self._cleanup_repos):
650 for repo_name in reversed(self._cleanup_repos):
651 self._fixture.destroy_repo(repo_name)
651 self._fixture.destroy_repo(repo_name)
652
652
653 def _add_commits_to_repo(self, repo, commits):
653 def _add_commits_to_repo(self, repo, commits):
654 commit_ids = _add_commits_to_repo(repo, commits)
654 commit_ids = _add_commits_to_repo(repo, commits)
655 if not commit_ids:
655 if not commit_ids:
656 return
656 return
657 self._commit_ids = commit_ids
657 self._commit_ids = commit_ids
658
658
659 # Creating refs for Git to allow fetching them from remote repository
659 # Creating refs for Git to allow fetching them from remote repository
660 if self.alias == 'git':
660 if self.alias == 'git':
661 refs = {}
661 refs = {}
662 for message in self._commit_ids:
662 for message in self._commit_ids:
663 # TODO: mikhail: do more special chars replacements
663 # TODO: mikhail: do more special chars replacements
664 ref_name = 'refs/test-refs/{}'.format(
664 ref_name = 'refs/test-refs/{}'.format(
665 message.replace(' ', ''))
665 message.replace(' ', ''))
666 refs[ref_name] = self._commit_ids[message]
666 refs[ref_name] = self._commit_ids[message]
667 self._create_refs(repo, refs)
667 self._create_refs(repo, refs)
668
668
669 def _create_refs(self, repo, refs):
669 def _create_refs(self, repo, refs):
670 for ref_name in refs:
670 for ref_name in refs:
671 repo.set_refs(ref_name, refs[ref_name])
671 repo.set_refs(ref_name, refs[ref_name])
672
672
673
673
674 @pytest.fixture
674 @pytest.fixture
675 def vcsbackend(request, backend_alias, tests_tmp_path, pylonsapp, test_repo):
675 def vcsbackend(request, backend_alias, tests_tmp_path, pylonsapp, test_repo):
676 """
676 """
677 Parametrized fixture which represents a single vcs backend implementation.
677 Parametrized fixture which represents a single vcs backend implementation.
678
678
679 See the fixture `backend` for more details. This one implements the same
679 See the fixture `backend` for more details. This one implements the same
680 concept, but on vcs level. So it does not provide model instances etc.
680 concept, but on vcs level. So it does not provide model instances etc.
681
681
682 Parameters are generated dynamically, see :func:`pytest_generate_tests`
682 Parameters are generated dynamically, see :func:`pytest_generate_tests`
683 for how this works.
683 for how this works.
684 """
684 """
685 if backend_alias not in request.config.getoption('--backends'):
685 if backend_alias not in request.config.getoption('--backends'):
686 pytest.skip("Backend %s not selected." % (backend_alias, ))
686 pytest.skip("Backend %s not selected." % (backend_alias, ))
687
687
688 utils.check_xfail_backends(request.node, backend_alias)
688 utils.check_xfail_backends(request.node, backend_alias)
689 utils.check_skip_backends(request.node, backend_alias)
689 utils.check_skip_backends(request.node, backend_alias)
690
690
691 repo_name = 'vcs_test_%s' % (backend_alias, )
691 repo_name = 'vcs_test_%s' % (backend_alias, )
692 repo_path = os.path.join(tests_tmp_path, repo_name)
692 repo_path = os.path.join(tests_tmp_path, repo_name)
693 backend = VcsBackend(
693 backend = VcsBackend(
694 alias=backend_alias,
694 alias=backend_alias,
695 repo_path=repo_path,
695 repo_path=repo_path,
696 test_name=request.node.name,
696 test_name=request.node.name,
697 test_repo_container=test_repo)
697 test_repo_container=test_repo)
698 request.addfinalizer(backend.cleanup)
698 request.addfinalizer(backend.cleanup)
699 return backend
699 return backend
700
700
701
701
702 @pytest.fixture
702 @pytest.fixture
703 def vcsbackend_git(request, tests_tmp_path, pylonsapp, test_repo):
703 def vcsbackend_git(request, tests_tmp_path, pylonsapp, test_repo):
704 return vcsbackend(request, 'git', tests_tmp_path, pylonsapp, test_repo)
704 return vcsbackend(request, 'git', tests_tmp_path, pylonsapp, test_repo)
705
705
706
706
707 @pytest.fixture
707 @pytest.fixture
708 def vcsbackend_hg(request, tests_tmp_path, pylonsapp, test_repo):
708 def vcsbackend_hg(request, tests_tmp_path, pylonsapp, test_repo):
709 return vcsbackend(request, 'hg', tests_tmp_path, pylonsapp, test_repo)
709 return vcsbackend(request, 'hg', tests_tmp_path, pylonsapp, test_repo)
710
710
711
711
712 @pytest.fixture
712 @pytest.fixture
713 def vcsbackend_svn(request, tests_tmp_path, pylonsapp, test_repo):
713 def vcsbackend_svn(request, tests_tmp_path, pylonsapp, test_repo):
714 return vcsbackend(request, 'svn', tests_tmp_path, pylonsapp, test_repo)
714 return vcsbackend(request, 'svn', tests_tmp_path, pylonsapp, test_repo)
715
715
716
716
717 @pytest.fixture
717 @pytest.fixture
718 def vcsbackend_random(vcsbackend_git):
718 def vcsbackend_random(vcsbackend_git):
719 """
719 """
720 Use this to express that your tests need "a vcsbackend".
720 Use this to express that your tests need "a vcsbackend".
721
721
722 The fixture `vcsbackend` would run the test multiple times for each
722 The fixture `vcsbackend` would run the test multiple times for each
723 available vcs backend which is a pure waste of time if the test is
723 available vcs backend which is a pure waste of time if the test is
724 independent of the vcs backend type.
724 independent of the vcs backend type.
725 """
725 """
726 # TODO: johbo: Change this to pick a random backend
726 # TODO: johbo: Change this to pick a random backend
727 return vcsbackend_git
727 return vcsbackend_git
728
728
729
729
730 @pytest.fixture
730 @pytest.fixture
731 def vcsbackend_stub(vcsbackend_git):
731 def vcsbackend_stub(vcsbackend_git):
732 """
732 """
733 Use this to express that your test just needs a stub of a vcsbackend.
733 Use this to express that your test just needs a stub of a vcsbackend.
734
734
735 Plan is to eventually implement an in-memory stub to speed tests up.
735 Plan is to eventually implement an in-memory stub to speed tests up.
736 """
736 """
737 return vcsbackend_git
737 return vcsbackend_git
738
738
739
739
740 class VcsBackend(object):
740 class VcsBackend(object):
741 """
741 """
742 Represents the test configuration for one supported vcs backend.
742 Represents the test configuration for one supported vcs backend.
743 """
743 """
744
744
745 invalid_repo_name = re.compile(r'[^0-9a-zA-Z]+')
745 invalid_repo_name = re.compile(r'[^0-9a-zA-Z]+')
746
746
747 def __init__(self, alias, repo_path, test_name, test_repo_container):
747 def __init__(self, alias, repo_path, test_name, test_repo_container):
748 self.alias = alias
748 self.alias = alias
749 self._repo_path = repo_path
749 self._repo_path = repo_path
750 self._cleanup_repos = []
750 self._cleanup_repos = []
751 self._test_name = test_name
751 self._test_name = test_name
752 self._test_repo_container = test_repo_container
752 self._test_repo_container = test_repo_container
753
753
754 def __getitem__(self, key):
754 def __getitem__(self, key):
755 return self._test_repo_container(key, self.alias).scm_instance()
755 return self._test_repo_container(key, self.alias).scm_instance()
756
756
757 @property
757 @property
758 def repo(self):
758 def repo(self):
759 """
759 """
760 Returns the "current" repository. This is the vcs_test repo of the last
760 Returns the "current" repository. This is the vcs_test repo of the last
761 repo which has been created.
761 repo which has been created.
762 """
762 """
763 Repository = get_backend(self.alias)
763 Repository = get_backend(self.alias)
764 return Repository(self._repo_path)
764 return Repository(self._repo_path)
765
765
766 @property
766 @property
767 def backend(self):
767 def backend(self):
768 """
768 """
769 Returns the backend implementation class.
769 Returns the backend implementation class.
770 """
770 """
771 return get_backend(self.alias)
771 return get_backend(self.alias)
772
772
773 def create_repo(self, commits=None, number_of_commits=0, _clone_repo=None):
773 def create_repo(self, commits=None, number_of_commits=0, _clone_repo=None):
774 repo_name = self._next_repo_name()
774 repo_name = self._next_repo_name()
775 self._repo_path = get_new_dir(repo_name)
775 self._repo_path = get_new_dir(repo_name)
776 repo_class = get_backend(self.alias)
776 repo_class = get_backend(self.alias)
777 src_url = None
777 src_url = None
778 if _clone_repo:
778 if _clone_repo:
779 src_url = _clone_repo.path
779 src_url = _clone_repo.path
780 repo = repo_class(self._repo_path, create=True, src_url=src_url)
780 repo = repo_class(self._repo_path, create=True, src_url=src_url)
781 self._cleanup_repos.append(repo)
781 self._cleanup_repos.append(repo)
782
782
783 commits = commits or [
783 commits = commits or [
784 {'message': 'Commit %s of %s' % (x, repo_name)}
784 {'message': 'Commit %s of %s' % (x, repo_name)}
785 for x in xrange(number_of_commits)]
785 for x in xrange(number_of_commits)]
786 _add_commits_to_repo(repo, commits)
786 _add_commits_to_repo(repo, commits)
787 return repo
787 return repo
788
788
789 def clone_repo(self, repo):
789 def clone_repo(self, repo):
790 return self.create_repo(_clone_repo=repo)
790 return self.create_repo(_clone_repo=repo)
791
791
792 def cleanup(self):
792 def cleanup(self):
793 for repo in self._cleanup_repos:
793 for repo in self._cleanup_repos:
794 shutil.rmtree(repo.path)
794 shutil.rmtree(repo.path)
795
795
796 def new_repo_path(self):
796 def new_repo_path(self):
797 repo_name = self._next_repo_name()
797 repo_name = self._next_repo_name()
798 self._repo_path = get_new_dir(repo_name)
798 self._repo_path = get_new_dir(repo_name)
799 return self._repo_path
799 return self._repo_path
800
800
801 def _next_repo_name(self):
801 def _next_repo_name(self):
802 return "%s_%s" % (
802 return "%s_%s" % (
803 self.invalid_repo_name.sub('_', self._test_name),
803 self.invalid_repo_name.sub('_', self._test_name),
804 len(self._cleanup_repos))
804 len(self._cleanup_repos))
805
805
806 def add_file(self, repo, filename, content='Test content\n'):
806 def add_file(self, repo, filename, content='Test content\n'):
807 imc = repo.in_memory_commit
807 imc = repo.in_memory_commit
808 imc.add(FileNode(filename, content=content))
808 imc.add(FileNode(filename, content=content))
809 imc.commit(
809 imc.commit(
810 message=u'Automatic commit from vcsbackend fixture',
810 message=u'Automatic commit from vcsbackend fixture',
811 author=u'Automatic')
811 author=u'Automatic')
812
812
813 def ensure_file(self, filename, content='Test content\n'):
813 def ensure_file(self, filename, content='Test content\n'):
814 assert self._cleanup_repos, "Avoid writing into vcs_test repos"
814 assert self._cleanup_repos, "Avoid writing into vcs_test repos"
815 self.add_file(self.repo, filename, content)
815 self.add_file(self.repo, filename, content)
816
816
817
817
818 def _add_commits_to_repo(vcs_repo, commits):
818 def _add_commits_to_repo(vcs_repo, commits):
819 commit_ids = {}
819 commit_ids = {}
820 if not commits:
820 if not commits:
821 return commit_ids
821 return commit_ids
822
822
823 imc = vcs_repo.in_memory_commit
823 imc = vcs_repo.in_memory_commit
824 commit = None
824 commit = None
825
825
826 for idx, commit in enumerate(commits):
826 for idx, commit in enumerate(commits):
827 message = unicode(commit.get('message', 'Commit %s' % idx))
827 message = unicode(commit.get('message', 'Commit %s' % idx))
828
828
829 for node in commit.get('added', []):
829 for node in commit.get('added', []):
830 imc.add(FileNode(node.path, content=node.content))
830 imc.add(FileNode(node.path, content=node.content))
831 for node in commit.get('changed', []):
831 for node in commit.get('changed', []):
832 imc.change(FileNode(node.path, content=node.content))
832 imc.change(FileNode(node.path, content=node.content))
833 for node in commit.get('removed', []):
833 for node in commit.get('removed', []):
834 imc.remove(FileNode(node.path))
834 imc.remove(FileNode(node.path))
835
835
836 parents = [
836 parents = [
837 vcs_repo.get_commit(commit_id=commit_ids[p])
837 vcs_repo.get_commit(commit_id=commit_ids[p])
838 for p in commit.get('parents', [])]
838 for p in commit.get('parents', [])]
839
839
840 operations = ('added', 'changed', 'removed')
840 operations = ('added', 'changed', 'removed')
841 if not any((commit.get(o) for o in operations)):
841 if not any((commit.get(o) for o in operations)):
842 imc.add(FileNode('file_%s' % idx, content=message))
842 imc.add(FileNode('file_%s' % idx, content=message))
843
843
844 commit = imc.commit(
844 commit = imc.commit(
845 message=message,
845 message=message,
846 author=unicode(commit.get('author', 'Automatic')),
846 author=unicode(commit.get('author', 'Automatic')),
847 date=commit.get('date'),
847 date=commit.get('date'),
848 branch=commit.get('branch'),
848 branch=commit.get('branch'),
849 parents=parents)
849 parents=parents)
850
850
851 commit_ids[commit.message] = commit.raw_id
851 commit_ids[commit.message] = commit.raw_id
852
852
853 return commit_ids
853 return commit_ids
854
854
855
855
856 @pytest.fixture
856 @pytest.fixture
857 def reposerver(request):
857 def reposerver(request):
858 """
858 """
859 Allows to serve a backend repository
859 Allows to serve a backend repository
860 """
860 """
861
861
862 repo_server = RepoServer()
862 repo_server = RepoServer()
863 request.addfinalizer(repo_server.cleanup)
863 request.addfinalizer(repo_server.cleanup)
864 return repo_server
864 return repo_server
865
865
866
866
867 class RepoServer(object):
867 class RepoServer(object):
868 """
868 """
869 Utility to serve a local repository for the duration of a test case.
869 Utility to serve a local repository for the duration of a test case.
870
870
871 Supports only Subversion so far.
871 Supports only Subversion so far.
872 """
872 """
873
873
874 url = None
874 url = None
875
875
876 def __init__(self):
876 def __init__(self):
877 self._cleanup_servers = []
877 self._cleanup_servers = []
878
878
879 def serve(self, vcsrepo):
879 def serve(self, vcsrepo):
880 if vcsrepo.alias != 'svn':
880 if vcsrepo.alias != 'svn':
881 raise TypeError("Backend %s not supported" % vcsrepo.alias)
881 raise TypeError("Backend %s not supported" % vcsrepo.alias)
882
882
883 proc = subprocess32.Popen(
883 proc = subprocess32.Popen(
884 ['svnserve', '-d', '--foreground', '--listen-host', 'localhost',
884 ['svnserve', '-d', '--foreground', '--listen-host', 'localhost',
885 '--root', vcsrepo.path])
885 '--root', vcsrepo.path])
886 self._cleanup_servers.append(proc)
886 self._cleanup_servers.append(proc)
887 self.url = 'svn://localhost'
887 self.url = 'svn://localhost'
888
888
889 def cleanup(self):
889 def cleanup(self):
890 for proc in self._cleanup_servers:
890 for proc in self._cleanup_servers:
891 proc.terminate()
891 proc.terminate()
892
892
893
893
894 @pytest.fixture
894 @pytest.fixture
895 def pr_util(backend, request, config_stub):
895 def pr_util(backend, request, config_stub):
896 """
896 """
897 Utility for tests of models and for functional tests around pull requests.
897 Utility for tests of models and for functional tests around pull requests.
898
898
899 It gives an instance of :class:`PRTestUtility` which provides various
899 It gives an instance of :class:`PRTestUtility` which provides various
900 utility methods around one pull request.
900 utility methods around one pull request.
901
901
902 This fixture uses `backend` and inherits its parameterization.
902 This fixture uses `backend` and inherits its parameterization.
903 """
903 """
904
904
905 util = PRTestUtility(backend)
905 util = PRTestUtility(backend)
906
906 request.addfinalizer(util.cleanup)
907 @request.addfinalizer
908 def cleanup():
909 util.cleanup()
910
907
911 return util
908 return util
912
909
913
910
914 class PRTestUtility(object):
911 class PRTestUtility(object):
915
912
916 pull_request = None
913 pull_request = None
917 pull_request_id = None
914 pull_request_id = None
918 mergeable_patcher = None
915 mergeable_patcher = None
919 mergeable_mock = None
916 mergeable_mock = None
920 notification_patcher = None
917 notification_patcher = None
921
918
922 def __init__(self, backend):
919 def __init__(self, backend):
923 self.backend = backend
920 self.backend = backend
924
921
925 def create_pull_request(
922 def create_pull_request(
926 self, commits=None, target_head=None, source_head=None,
923 self, commits=None, target_head=None, source_head=None,
927 revisions=None, approved=False, author=None, mergeable=False,
924 revisions=None, approved=False, author=None, mergeable=False,
928 enable_notifications=True, name_suffix=u'', reviewers=None,
925 enable_notifications=True, name_suffix=u'', reviewers=None,
929 title=u"Test", description=u"Description"):
926 title=u"Test", description=u"Description"):
930 self.set_mergeable(mergeable)
927 self.set_mergeable(mergeable)
931 if not enable_notifications:
928 if not enable_notifications:
932 # mock notification side effect
929 # mock notification side effect
933 self.notification_patcher = mock.patch(
930 self.notification_patcher = mock.patch(
934 'rhodecode.model.notification.NotificationModel.create')
931 'rhodecode.model.notification.NotificationModel.create')
935 self.notification_patcher.start()
932 self.notification_patcher.start()
936
933
937 if not self.pull_request:
934 if not self.pull_request:
938 if not commits:
935 if not commits:
939 commits = [
936 commits = [
940 {'message': 'c1'},
937 {'message': 'c1'},
941 {'message': 'c2'},
938 {'message': 'c2'},
942 {'message': 'c3'},
939 {'message': 'c3'},
943 ]
940 ]
944 target_head = 'c1'
941 target_head = 'c1'
945 source_head = 'c2'
942 source_head = 'c2'
946 revisions = ['c2']
943 revisions = ['c2']
947
944
948 self.commit_ids = self.backend.create_master_repo(commits)
945 self.commit_ids = self.backend.create_master_repo(commits)
949 self.target_repository = self.backend.create_repo(
946 self.target_repository = self.backend.create_repo(
950 heads=[target_head], name_suffix=name_suffix)
947 heads=[target_head], name_suffix=name_suffix)
951 self.source_repository = self.backend.create_repo(
948 self.source_repository = self.backend.create_repo(
952 heads=[source_head], name_suffix=name_suffix)
949 heads=[source_head], name_suffix=name_suffix)
953 self.author = author or UserModel().get_by_username(
950 self.author = author or UserModel().get_by_username(
954 TEST_USER_ADMIN_LOGIN)
951 TEST_USER_ADMIN_LOGIN)
955
952
956 model = PullRequestModel()
953 model = PullRequestModel()
957 self.create_parameters = {
954 self.create_parameters = {
958 'created_by': self.author,
955 'created_by': self.author,
959 'source_repo': self.source_repository.repo_name,
956 'source_repo': self.source_repository.repo_name,
960 'source_ref': self._default_branch_reference(source_head),
957 'source_ref': self._default_branch_reference(source_head),
961 'target_repo': self.target_repository.repo_name,
958 'target_repo': self.target_repository.repo_name,
962 'target_ref': self._default_branch_reference(target_head),
959 'target_ref': self._default_branch_reference(target_head),
963 'revisions': [self.commit_ids[r] for r in revisions],
960 'revisions': [self.commit_ids[r] for r in revisions],
964 'reviewers': reviewers or self._get_reviewers(),
961 'reviewers': reviewers or self._get_reviewers(),
965 'title': title,
962 'title': title,
966 'description': description,
963 'description': description,
967 }
964 }
968 self.pull_request = model.create(**self.create_parameters)
965 self.pull_request = model.create(**self.create_parameters)
969 assert model.get_versions(self.pull_request) == []
966 assert model.get_versions(self.pull_request) == []
970
967
971 self.pull_request_id = self.pull_request.pull_request_id
968 self.pull_request_id = self.pull_request.pull_request_id
972
969
973 if approved:
970 if approved:
974 self.approve()
971 self.approve()
975
972
976 Session().add(self.pull_request)
973 Session().add(self.pull_request)
977 Session().commit()
974 Session().commit()
978
975
979 return self.pull_request
976 return self.pull_request
980
977
981 def approve(self):
978 def approve(self):
982 self.create_status_votes(
979 self.create_status_votes(
983 ChangesetStatus.STATUS_APPROVED,
980 ChangesetStatus.STATUS_APPROVED,
984 *self.pull_request.reviewers)
981 *self.pull_request.reviewers)
985
982
986 def close(self):
983 def close(self):
987 PullRequestModel().close_pull_request(self.pull_request, self.author)
984 PullRequestModel().close_pull_request(self.pull_request, self.author)
988
985
989 def _default_branch_reference(self, commit_message):
986 def _default_branch_reference(self, commit_message):
990 reference = '%s:%s:%s' % (
987 reference = '%s:%s:%s' % (
991 'branch',
988 'branch',
992 self.backend.default_branch_name,
989 self.backend.default_branch_name,
993 self.commit_ids[commit_message])
990 self.commit_ids[commit_message])
994 return reference
991 return reference
995
992
996 def _get_reviewers(self):
993 def _get_reviewers(self):
997 return [
994 return [
998 (TEST_USER_REGULAR_LOGIN, ['default1'], False),
995 (TEST_USER_REGULAR_LOGIN, ['default1'], False),
999 (TEST_USER_REGULAR2_LOGIN, ['default2'], False),
996 (TEST_USER_REGULAR2_LOGIN, ['default2'], False),
1000 ]
997 ]
1001
998
1002 def update_source_repository(self, head=None):
999 def update_source_repository(self, head=None):
1003 heads = [head or 'c3']
1000 heads = [head or 'c3']
1004 self.backend.pull_heads(self.source_repository, heads=heads)
1001 self.backend.pull_heads(self.source_repository, heads=heads)
1005
1002
1006 def add_one_commit(self, head=None):
1003 def add_one_commit(self, head=None):
1007 self.update_source_repository(head=head)
1004 self.update_source_repository(head=head)
1008 old_commit_ids = set(self.pull_request.revisions)
1005 old_commit_ids = set(self.pull_request.revisions)
1009 PullRequestModel().update_commits(self.pull_request)
1006 PullRequestModel().update_commits(self.pull_request)
1010 commit_ids = set(self.pull_request.revisions)
1007 commit_ids = set(self.pull_request.revisions)
1011 new_commit_ids = commit_ids - old_commit_ids
1008 new_commit_ids = commit_ids - old_commit_ids
1012 assert len(new_commit_ids) == 1
1009 assert len(new_commit_ids) == 1
1013 return new_commit_ids.pop()
1010 return new_commit_ids.pop()
1014
1011
1015 def remove_one_commit(self):
1012 def remove_one_commit(self):
1016 assert len(self.pull_request.revisions) == 2
1013 assert len(self.pull_request.revisions) == 2
1017 source_vcs = self.source_repository.scm_instance()
1014 source_vcs = self.source_repository.scm_instance()
1018 removed_commit_id = source_vcs.commit_ids[-1]
1015 removed_commit_id = source_vcs.commit_ids[-1]
1019
1016
1020 # TODO: johbo: Git and Mercurial have an inconsistent vcs api here,
1017 # TODO: johbo: Git and Mercurial have an inconsistent vcs api here,
1021 # remove the if once that's sorted out.
1018 # remove the if once that's sorted out.
1022 if self.backend.alias == "git":
1019 if self.backend.alias == "git":
1023 kwargs = {'branch_name': self.backend.default_branch_name}
1020 kwargs = {'branch_name': self.backend.default_branch_name}
1024 else:
1021 else:
1025 kwargs = {}
1022 kwargs = {}
1026 source_vcs.strip(removed_commit_id, **kwargs)
1023 source_vcs.strip(removed_commit_id, **kwargs)
1027
1024
1028 PullRequestModel().update_commits(self.pull_request)
1025 PullRequestModel().update_commits(self.pull_request)
1029 assert len(self.pull_request.revisions) == 1
1026 assert len(self.pull_request.revisions) == 1
1030 return removed_commit_id
1027 return removed_commit_id
1031
1028
1032 def create_comment(self, linked_to=None):
1029 def create_comment(self, linked_to=None):
1033 comment = CommentsModel().create(
1030 comment = CommentsModel().create(
1034 text=u"Test comment",
1031 text=u"Test comment",
1035 repo=self.target_repository.repo_name,
1032 repo=self.target_repository.repo_name,
1036 user=self.author,
1033 user=self.author,
1037 pull_request=self.pull_request)
1034 pull_request=self.pull_request)
1038 assert comment.pull_request_version_id is None
1035 assert comment.pull_request_version_id is None
1039
1036
1040 if linked_to:
1037 if linked_to:
1041 PullRequestModel()._link_comments_to_version(linked_to)
1038 PullRequestModel()._link_comments_to_version(linked_to)
1042
1039
1043 return comment
1040 return comment
1044
1041
1045 def create_inline_comment(
1042 def create_inline_comment(
1046 self, linked_to=None, line_no=u'n1', file_path='file_1'):
1043 self, linked_to=None, line_no=u'n1', file_path='file_1'):
1047 comment = CommentsModel().create(
1044 comment = CommentsModel().create(
1048 text=u"Test comment",
1045 text=u"Test comment",
1049 repo=self.target_repository.repo_name,
1046 repo=self.target_repository.repo_name,
1050 user=self.author,
1047 user=self.author,
1051 line_no=line_no,
1048 line_no=line_no,
1052 f_path=file_path,
1049 f_path=file_path,
1053 pull_request=self.pull_request)
1050 pull_request=self.pull_request)
1054 assert comment.pull_request_version_id is None
1051 assert comment.pull_request_version_id is None
1055
1052
1056 if linked_to:
1053 if linked_to:
1057 PullRequestModel()._link_comments_to_version(linked_to)
1054 PullRequestModel()._link_comments_to_version(linked_to)
1058
1055
1059 return comment
1056 return comment
1060
1057
1061 def create_version_of_pull_request(self):
1058 def create_version_of_pull_request(self):
1062 pull_request = self.create_pull_request()
1059 pull_request = self.create_pull_request()
1063 version = PullRequestModel()._create_version_from_snapshot(
1060 version = PullRequestModel()._create_version_from_snapshot(
1064 pull_request)
1061 pull_request)
1065 return version
1062 return version
1066
1063
1067 def create_status_votes(self, status, *reviewers):
1064 def create_status_votes(self, status, *reviewers):
1068 for reviewer in reviewers:
1065 for reviewer in reviewers:
1069 ChangesetStatusModel().set_status(
1066 ChangesetStatusModel().set_status(
1070 repo=self.pull_request.target_repo,
1067 repo=self.pull_request.target_repo,
1071 status=status,
1068 status=status,
1072 user=reviewer.user_id,
1069 user=reviewer.user_id,
1073 pull_request=self.pull_request)
1070 pull_request=self.pull_request)
1074
1071
1075 def set_mergeable(self, value):
1072 def set_mergeable(self, value):
1076 if not self.mergeable_patcher:
1073 if not self.mergeable_patcher:
1077 self.mergeable_patcher = mock.patch.object(
1074 self.mergeable_patcher = mock.patch.object(
1078 VcsSettingsModel, 'get_general_settings')
1075 VcsSettingsModel, 'get_general_settings')
1079 self.mergeable_mock = self.mergeable_patcher.start()
1076 self.mergeable_mock = self.mergeable_patcher.start()
1080 self.mergeable_mock.return_value = {
1077 self.mergeable_mock.return_value = {
1081 'rhodecode_pr_merge_enabled': value}
1078 'rhodecode_pr_merge_enabled': value}
1082
1079
1083 def cleanup(self):
1080 def cleanup(self):
1084 # In case the source repository is already cleaned up, the pull
1081 # In case the source repository is already cleaned up, the pull
1085 # request will already be deleted.
1082 # request will already be deleted.
1086 pull_request = PullRequest().get(self.pull_request_id)
1083 pull_request = PullRequest().get(self.pull_request_id)
1087 if pull_request:
1084 if pull_request:
1088 PullRequestModel().delete(pull_request, pull_request.author)
1085 PullRequestModel().delete(pull_request, pull_request.author)
1089 Session().commit()
1086 Session().commit()
1090
1087
1091 if self.notification_patcher:
1088 if self.notification_patcher:
1092 self.notification_patcher.stop()
1089 self.notification_patcher.stop()
1093
1090
1094 if self.mergeable_patcher:
1091 if self.mergeable_patcher:
1095 self.mergeable_patcher.stop()
1092 self.mergeable_patcher.stop()
1096
1093
1097
1094
1098 @pytest.fixture
1095 @pytest.fixture
1099 def user_admin(pylonsapp):
1096 def user_admin(pylonsapp):
1100 """
1097 """
1101 Provides the default admin test user as an instance of `db.User`.
1098 Provides the default admin test user as an instance of `db.User`.
1102 """
1099 """
1103 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
1100 user = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
1104 return user
1101 return user
1105
1102
1106
1103
1107 @pytest.fixture
1104 @pytest.fixture
1108 def user_regular(pylonsapp):
1105 def user_regular(pylonsapp):
1109 """
1106 """
1110 Provides the default regular test user as an instance of `db.User`.
1107 Provides the default regular test user as an instance of `db.User`.
1111 """
1108 """
1112 user = UserModel().get_by_username(TEST_USER_REGULAR_LOGIN)
1109 user = UserModel().get_by_username(TEST_USER_REGULAR_LOGIN)
1113 return user
1110 return user
1114
1111
1115
1112
1116 @pytest.fixture
1113 @pytest.fixture
1117 def user_util(request, pylonsapp):
1114 def user_util(request, pylonsapp):
1118 """
1115 """
1119 Provides a wired instance of `UserUtility` with integrated cleanup.
1116 Provides a wired instance of `UserUtility` with integrated cleanup.
1120 """
1117 """
1121 utility = UserUtility(test_name=request.node.name)
1118 utility = UserUtility(test_name=request.node.name)
1122 request.addfinalizer(utility.cleanup)
1119 request.addfinalizer(utility.cleanup)
1123 return utility
1120 return utility
1124
1121
1125
1122
1126 # TODO: johbo: Split this up into utilities per domain or something similar
1123 # TODO: johbo: Split this up into utilities per domain or something similar
1127 class UserUtility(object):
1124 class UserUtility(object):
1128
1125
1129 def __init__(self, test_name="test"):
1126 def __init__(self, test_name="test"):
1130 self._test_name = self._sanitize_name(test_name)
1127 self._test_name = self._sanitize_name(test_name)
1131 self.fixture = Fixture()
1128 self.fixture = Fixture()
1132 self.repo_group_ids = []
1129 self.repo_group_ids = []
1133 self.repos_ids = []
1130 self.repos_ids = []
1134 self.user_ids = []
1131 self.user_ids = []
1135 self.user_group_ids = []
1132 self.user_group_ids = []
1136 self.user_repo_permission_ids = []
1133 self.user_repo_permission_ids = []
1137 self.user_group_repo_permission_ids = []
1134 self.user_group_repo_permission_ids = []
1138 self.user_repo_group_permission_ids = []
1135 self.user_repo_group_permission_ids = []
1139 self.user_group_repo_group_permission_ids = []
1136 self.user_group_repo_group_permission_ids = []
1140 self.user_user_group_permission_ids = []
1137 self.user_user_group_permission_ids = []
1141 self.user_group_user_group_permission_ids = []
1138 self.user_group_user_group_permission_ids = []
1142 self.user_permissions = []
1139 self.user_permissions = []
1143
1140
1144 def _sanitize_name(self, name):
1141 def _sanitize_name(self, name):
1145 for char in ['[', ']']:
1142 for char in ['[', ']']:
1146 name = name.replace(char, '_')
1143 name = name.replace(char, '_')
1147 return name
1144 return name
1148
1145
1149 def create_repo_group(
1146 def create_repo_group(
1150 self, owner=TEST_USER_ADMIN_LOGIN, auto_cleanup=True):
1147 self, owner=TEST_USER_ADMIN_LOGIN, auto_cleanup=True):
1151 group_name = "{prefix}_repogroup_{count}".format(
1148 group_name = "{prefix}_repogroup_{count}".format(
1152 prefix=self._test_name,
1149 prefix=self._test_name,
1153 count=len(self.repo_group_ids))
1150 count=len(self.repo_group_ids))
1154 repo_group = self.fixture.create_repo_group(
1151 repo_group = self.fixture.create_repo_group(
1155 group_name, cur_user=owner)
1152 group_name, cur_user=owner)
1156 if auto_cleanup:
1153 if auto_cleanup:
1157 self.repo_group_ids.append(repo_group.group_id)
1154 self.repo_group_ids.append(repo_group.group_id)
1158 return repo_group
1155 return repo_group
1159
1156
1160 def create_repo(self, owner=TEST_USER_ADMIN_LOGIN, parent=None,
1157 def create_repo(self, owner=TEST_USER_ADMIN_LOGIN, parent=None,
1161 auto_cleanup=True, repo_type='hg'):
1158 auto_cleanup=True, repo_type='hg'):
1162 repo_name = "{prefix}_repository_{count}".format(
1159 repo_name = "{prefix}_repository_{count}".format(
1163 prefix=self._test_name,
1160 prefix=self._test_name,
1164 count=len(self.repos_ids))
1161 count=len(self.repos_ids))
1165
1162
1166 repository = self.fixture.create_repo(
1163 repository = self.fixture.create_repo(
1167 repo_name, cur_user=owner, repo_group=parent, repo_type=repo_type)
1164 repo_name, cur_user=owner, repo_group=parent, repo_type=repo_type)
1168 if auto_cleanup:
1165 if auto_cleanup:
1169 self.repos_ids.append(repository.repo_id)
1166 self.repos_ids.append(repository.repo_id)
1170 return repository
1167 return repository
1171
1168
1172 def create_user(self, auto_cleanup=True, **kwargs):
1169 def create_user(self, auto_cleanup=True, **kwargs):
1173 user_name = "{prefix}_user_{count}".format(
1170 user_name = "{prefix}_user_{count}".format(
1174 prefix=self._test_name,
1171 prefix=self._test_name,
1175 count=len(self.user_ids))
1172 count=len(self.user_ids))
1176 user = self.fixture.create_user(user_name, **kwargs)
1173 user = self.fixture.create_user(user_name, **kwargs)
1177 if auto_cleanup:
1174 if auto_cleanup:
1178 self.user_ids.append(user.user_id)
1175 self.user_ids.append(user.user_id)
1179 return user
1176 return user
1180
1177
1181 def create_user_with_group(self):
1178 def create_user_with_group(self):
1182 user = self.create_user()
1179 user = self.create_user()
1183 user_group = self.create_user_group(members=[user])
1180 user_group = self.create_user_group(members=[user])
1184 return user, user_group
1181 return user, user_group
1185
1182
1186 def create_user_group(self, owner=TEST_USER_ADMIN_LOGIN, members=None,
1183 def create_user_group(self, owner=TEST_USER_ADMIN_LOGIN, members=None,
1187 auto_cleanup=True, **kwargs):
1184 auto_cleanup=True, **kwargs):
1188 group_name = "{prefix}_usergroup_{count}".format(
1185 group_name = "{prefix}_usergroup_{count}".format(
1189 prefix=self._test_name,
1186 prefix=self._test_name,
1190 count=len(self.user_group_ids))
1187 count=len(self.user_group_ids))
1191 user_group = self.fixture.create_user_group(
1188 user_group = self.fixture.create_user_group(
1192 group_name, cur_user=owner, **kwargs)
1189 group_name, cur_user=owner, **kwargs)
1193
1190
1194 if auto_cleanup:
1191 if auto_cleanup:
1195 self.user_group_ids.append(user_group.users_group_id)
1192 self.user_group_ids.append(user_group.users_group_id)
1196 if members:
1193 if members:
1197 for user in members:
1194 for user in members:
1198 UserGroupModel().add_user_to_group(user_group, user)
1195 UserGroupModel().add_user_to_group(user_group, user)
1199 return user_group
1196 return user_group
1200
1197
1201 def grant_user_permission(self, user_name, permission_name):
1198 def grant_user_permission(self, user_name, permission_name):
1202 self._inherit_default_user_permissions(user_name, False)
1199 self._inherit_default_user_permissions(user_name, False)
1203 self.user_permissions.append((user_name, permission_name))
1200 self.user_permissions.append((user_name, permission_name))
1204
1201
1205 def grant_user_permission_to_repo_group(
1202 def grant_user_permission_to_repo_group(
1206 self, repo_group, user, permission_name):
1203 self, repo_group, user, permission_name):
1207 permission = RepoGroupModel().grant_user_permission(
1204 permission = RepoGroupModel().grant_user_permission(
1208 repo_group, user, permission_name)
1205 repo_group, user, permission_name)
1209 self.user_repo_group_permission_ids.append(
1206 self.user_repo_group_permission_ids.append(
1210 (repo_group.group_id, user.user_id))
1207 (repo_group.group_id, user.user_id))
1211 return permission
1208 return permission
1212
1209
1213 def grant_user_group_permission_to_repo_group(
1210 def grant_user_group_permission_to_repo_group(
1214 self, repo_group, user_group, permission_name):
1211 self, repo_group, user_group, permission_name):
1215 permission = RepoGroupModel().grant_user_group_permission(
1212 permission = RepoGroupModel().grant_user_group_permission(
1216 repo_group, user_group, permission_name)
1213 repo_group, user_group, permission_name)
1217 self.user_group_repo_group_permission_ids.append(
1214 self.user_group_repo_group_permission_ids.append(
1218 (repo_group.group_id, user_group.users_group_id))
1215 (repo_group.group_id, user_group.users_group_id))
1219 return permission
1216 return permission
1220
1217
1221 def grant_user_permission_to_repo(
1218 def grant_user_permission_to_repo(
1222 self, repo, user, permission_name):
1219 self, repo, user, permission_name):
1223 permission = RepoModel().grant_user_permission(
1220 permission = RepoModel().grant_user_permission(
1224 repo, user, permission_name)
1221 repo, user, permission_name)
1225 self.user_repo_permission_ids.append(
1222 self.user_repo_permission_ids.append(
1226 (repo.repo_id, user.user_id))
1223 (repo.repo_id, user.user_id))
1227 return permission
1224 return permission
1228
1225
1229 def grant_user_group_permission_to_repo(
1226 def grant_user_group_permission_to_repo(
1230 self, repo, user_group, permission_name):
1227 self, repo, user_group, permission_name):
1231 permission = RepoModel().grant_user_group_permission(
1228 permission = RepoModel().grant_user_group_permission(
1232 repo, user_group, permission_name)
1229 repo, user_group, permission_name)
1233 self.user_group_repo_permission_ids.append(
1230 self.user_group_repo_permission_ids.append(
1234 (repo.repo_id, user_group.users_group_id))
1231 (repo.repo_id, user_group.users_group_id))
1235 return permission
1232 return permission
1236
1233
1237 def grant_user_permission_to_user_group(
1234 def grant_user_permission_to_user_group(
1238 self, target_user_group, user, permission_name):
1235 self, target_user_group, user, permission_name):
1239 permission = UserGroupModel().grant_user_permission(
1236 permission = UserGroupModel().grant_user_permission(
1240 target_user_group, user, permission_name)
1237 target_user_group, user, permission_name)
1241 self.user_user_group_permission_ids.append(
1238 self.user_user_group_permission_ids.append(
1242 (target_user_group.users_group_id, user.user_id))
1239 (target_user_group.users_group_id, user.user_id))
1243 return permission
1240 return permission
1244
1241
1245 def grant_user_group_permission_to_user_group(
1242 def grant_user_group_permission_to_user_group(
1246 self, target_user_group, user_group, permission_name):
1243 self, target_user_group, user_group, permission_name):
1247 permission = UserGroupModel().grant_user_group_permission(
1244 permission = UserGroupModel().grant_user_group_permission(
1248 target_user_group, user_group, permission_name)
1245 target_user_group, user_group, permission_name)
1249 self.user_group_user_group_permission_ids.append(
1246 self.user_group_user_group_permission_ids.append(
1250 (target_user_group.users_group_id, user_group.users_group_id))
1247 (target_user_group.users_group_id, user_group.users_group_id))
1251 return permission
1248 return permission
1252
1249
1253 def revoke_user_permission(self, user_name, permission_name):
1250 def revoke_user_permission(self, user_name, permission_name):
1254 self._inherit_default_user_permissions(user_name, True)
1251 self._inherit_default_user_permissions(user_name, True)
1255 UserModel().revoke_perm(user_name, permission_name)
1252 UserModel().revoke_perm(user_name, permission_name)
1256
1253
1257 def _inherit_default_user_permissions(self, user_name, value):
1254 def _inherit_default_user_permissions(self, user_name, value):
1258 user = UserModel().get_by_username(user_name)
1255 user = UserModel().get_by_username(user_name)
1259 user.inherit_default_permissions = value
1256 user.inherit_default_permissions = value
1260 Session().add(user)
1257 Session().add(user)
1261 Session().commit()
1258 Session().commit()
1262
1259
1263 def cleanup(self):
1260 def cleanup(self):
1264 self._cleanup_permissions()
1261 self._cleanup_permissions()
1265 self._cleanup_repos()
1262 self._cleanup_repos()
1266 self._cleanup_repo_groups()
1263 self._cleanup_repo_groups()
1267 self._cleanup_user_groups()
1264 self._cleanup_user_groups()
1268 self._cleanup_users()
1265 self._cleanup_users()
1269
1266
1270 def _cleanup_permissions(self):
1267 def _cleanup_permissions(self):
1271 if self.user_permissions:
1268 if self.user_permissions:
1272 for user_name, permission_name in self.user_permissions:
1269 for user_name, permission_name in self.user_permissions:
1273 self.revoke_user_permission(user_name, permission_name)
1270 self.revoke_user_permission(user_name, permission_name)
1274
1271
1275 for permission in self.user_repo_permission_ids:
1272 for permission in self.user_repo_permission_ids:
1276 RepoModel().revoke_user_permission(*permission)
1273 RepoModel().revoke_user_permission(*permission)
1277
1274
1278 for permission in self.user_group_repo_permission_ids:
1275 for permission in self.user_group_repo_permission_ids:
1279 RepoModel().revoke_user_group_permission(*permission)
1276 RepoModel().revoke_user_group_permission(*permission)
1280
1277
1281 for permission in self.user_repo_group_permission_ids:
1278 for permission in self.user_repo_group_permission_ids:
1282 RepoGroupModel().revoke_user_permission(*permission)
1279 RepoGroupModel().revoke_user_permission(*permission)
1283
1280
1284 for permission in self.user_group_repo_group_permission_ids:
1281 for permission in self.user_group_repo_group_permission_ids:
1285 RepoGroupModel().revoke_user_group_permission(*permission)
1282 RepoGroupModel().revoke_user_group_permission(*permission)
1286
1283
1287 for permission in self.user_user_group_permission_ids:
1284 for permission in self.user_user_group_permission_ids:
1288 UserGroupModel().revoke_user_permission(*permission)
1285 UserGroupModel().revoke_user_permission(*permission)
1289
1286
1290 for permission in self.user_group_user_group_permission_ids:
1287 for permission in self.user_group_user_group_permission_ids:
1291 UserGroupModel().revoke_user_group_permission(*permission)
1288 UserGroupModel().revoke_user_group_permission(*permission)
1292
1289
1293 def _cleanup_repo_groups(self):
1290 def _cleanup_repo_groups(self):
1294 def _repo_group_compare(first_group_id, second_group_id):
1291 def _repo_group_compare(first_group_id, second_group_id):
1295 """
1292 """
1296 Gives higher priority to the groups with the most complex paths
1293 Gives higher priority to the groups with the most complex paths
1297 """
1294 """
1298 first_group = RepoGroup.get(first_group_id)
1295 first_group = RepoGroup.get(first_group_id)
1299 second_group = RepoGroup.get(second_group_id)
1296 second_group = RepoGroup.get(second_group_id)
1300 first_group_parts = (
1297 first_group_parts = (
1301 len(first_group.group_name.split('/')) if first_group else 0)
1298 len(first_group.group_name.split('/')) if first_group else 0)
1302 second_group_parts = (
1299 second_group_parts = (
1303 len(second_group.group_name.split('/')) if second_group else 0)
1300 len(second_group.group_name.split('/')) if second_group else 0)
1304 return cmp(second_group_parts, first_group_parts)
1301 return cmp(second_group_parts, first_group_parts)
1305
1302
1306 sorted_repo_group_ids = sorted(
1303 sorted_repo_group_ids = sorted(
1307 self.repo_group_ids, cmp=_repo_group_compare)
1304 self.repo_group_ids, cmp=_repo_group_compare)
1308 for repo_group_id in sorted_repo_group_ids:
1305 for repo_group_id in sorted_repo_group_ids:
1309 self.fixture.destroy_repo_group(repo_group_id)
1306 self.fixture.destroy_repo_group(repo_group_id)
1310
1307
1311 def _cleanup_repos(self):
1308 def _cleanup_repos(self):
1312 sorted_repos_ids = sorted(self.repos_ids)
1309 sorted_repos_ids = sorted(self.repos_ids)
1313 for repo_id in sorted_repos_ids:
1310 for repo_id in sorted_repos_ids:
1314 self.fixture.destroy_repo(repo_id)
1311 self.fixture.destroy_repo(repo_id)
1315
1312
1316 def _cleanup_user_groups(self):
1313 def _cleanup_user_groups(self):
1317 def _user_group_compare(first_group_id, second_group_id):
1314 def _user_group_compare(first_group_id, second_group_id):
1318 """
1315 """
1319 Gives higher priority to the groups with the most complex paths
1316 Gives higher priority to the groups with the most complex paths
1320 """
1317 """
1321 first_group = UserGroup.get(first_group_id)
1318 first_group = UserGroup.get(first_group_id)
1322 second_group = UserGroup.get(second_group_id)
1319 second_group = UserGroup.get(second_group_id)
1323 first_group_parts = (
1320 first_group_parts = (
1324 len(first_group.users_group_name.split('/'))
1321 len(first_group.users_group_name.split('/'))
1325 if first_group else 0)
1322 if first_group else 0)
1326 second_group_parts = (
1323 second_group_parts = (
1327 len(second_group.users_group_name.split('/'))
1324 len(second_group.users_group_name.split('/'))
1328 if second_group else 0)
1325 if second_group else 0)
1329 return cmp(second_group_parts, first_group_parts)
1326 return cmp(second_group_parts, first_group_parts)
1330
1327
1331 sorted_user_group_ids = sorted(
1328 sorted_user_group_ids = sorted(
1332 self.user_group_ids, cmp=_user_group_compare)
1329 self.user_group_ids, cmp=_user_group_compare)
1333 for user_group_id in sorted_user_group_ids:
1330 for user_group_id in sorted_user_group_ids:
1334 self.fixture.destroy_user_group(user_group_id)
1331 self.fixture.destroy_user_group(user_group_id)
1335
1332
1336 def _cleanup_users(self):
1333 def _cleanup_users(self):
1337 for user_id in self.user_ids:
1334 for user_id in self.user_ids:
1338 self.fixture.destroy_user(user_id)
1335 self.fixture.destroy_user(user_id)
1339
1336
1340
1337
1341 # TODO: Think about moving this into a pytest-pyro package and make it a
1338 # TODO: Think about moving this into a pytest-pyro package and make it a
1342 # pytest plugin
1339 # pytest plugin
1343 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
1340 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
1344 def pytest_runtest_makereport(item, call):
1341 def pytest_runtest_makereport(item, call):
1345 """
1342 """
1346 Adding the remote traceback if the exception has this information.
1343 Adding the remote traceback if the exception has this information.
1347
1344
1348 VCSServer attaches this information as the attribute `_vcs_server_traceback`
1345 VCSServer attaches this information as the attribute `_vcs_server_traceback`
1349 to the exception instance.
1346 to the exception instance.
1350 """
1347 """
1351 outcome = yield
1348 outcome = yield
1352 report = outcome.get_result()
1349 report = outcome.get_result()
1353 if call.excinfo:
1350 if call.excinfo:
1354 _add_vcsserver_remote_traceback(report, call.excinfo.value)
1351 _add_vcsserver_remote_traceback(report, call.excinfo.value)
1355
1352
1356
1353
1357 def _add_vcsserver_remote_traceback(report, exc):
1354 def _add_vcsserver_remote_traceback(report, exc):
1358 vcsserver_traceback = getattr(exc, '_vcs_server_traceback', None)
1355 vcsserver_traceback = getattr(exc, '_vcs_server_traceback', None)
1359
1356
1360 if vcsserver_traceback:
1357 if vcsserver_traceback:
1361 section = 'VCSServer remote traceback ' + report.when
1358 section = 'VCSServer remote traceback ' + report.when
1362 report.sections.append((section, vcsserver_traceback))
1359 report.sections.append((section, vcsserver_traceback))
1363
1360
1364
1361
1365 @pytest.fixture(scope='session')
1362 @pytest.fixture(scope='session')
1366 def testrun():
1363 def testrun():
1367 return {
1364 return {
1368 'uuid': uuid.uuid4(),
1365 'uuid': uuid.uuid4(),
1369 'start': datetime.datetime.utcnow().isoformat(),
1366 'start': datetime.datetime.utcnow().isoformat(),
1370 'timestamp': int(time.time()),
1367 'timestamp': int(time.time()),
1371 }
1368 }
1372
1369
1373
1370
1374 @pytest.fixture(autouse=True)
1371 @pytest.fixture(autouse=True)
1375 def collect_appenlight_stats(request, testrun):
1372 def collect_appenlight_stats(request, testrun):
1376 """
1373 """
1377 This fixture reports memory consumtion of single tests.
1374 This fixture reports memory consumtion of single tests.
1378
1375
1379 It gathers data based on `psutil` and sends them to Appenlight. The option
1376 It gathers data based on `psutil` and sends them to Appenlight. The option
1380 ``--ae`` has te be used to enable this fixture and the API key for your
1377 ``--ae`` has te be used to enable this fixture and the API key for your
1381 application has to be provided in ``--ae-key``.
1378 application has to be provided in ``--ae-key``.
1382 """
1379 """
1383 try:
1380 try:
1384 # cygwin cannot have yet psutil support.
1381 # cygwin cannot have yet psutil support.
1385 import psutil
1382 import psutil
1386 except ImportError:
1383 except ImportError:
1387 return
1384 return
1388
1385
1389 if not request.config.getoption('--appenlight'):
1386 if not request.config.getoption('--appenlight'):
1390 return
1387 return
1391 else:
1388 else:
1392 # Only request the pylonsapp fixture if appenlight tracking is
1389 # Only request the pylonsapp fixture if appenlight tracking is
1393 # enabled. This will speed up a test run of unit tests by 2 to 3
1390 # enabled. This will speed up a test run of unit tests by 2 to 3
1394 # seconds if appenlight is not enabled.
1391 # seconds if appenlight is not enabled.
1395 pylonsapp = request.getfuncargvalue("pylonsapp")
1392 pylonsapp = request.getfuncargvalue("pylonsapp")
1396 url = '{}/api/logs'.format(request.config.getoption('--appenlight-url'))
1393 url = '{}/api/logs'.format(request.config.getoption('--appenlight-url'))
1397 client = AppenlightClient(
1394 client = AppenlightClient(
1398 url=url,
1395 url=url,
1399 api_key=request.config.getoption('--appenlight-api-key'),
1396 api_key=request.config.getoption('--appenlight-api-key'),
1400 namespace=request.node.nodeid,
1397 namespace=request.node.nodeid,
1401 request=str(testrun['uuid']),
1398 request=str(testrun['uuid']),
1402 testrun=testrun)
1399 testrun=testrun)
1403
1400
1404 client.collect({
1401 client.collect({
1405 'message': "Starting",
1402 'message': "Starting",
1406 })
1403 })
1407
1404
1408 server_and_port = pylonsapp.config['vcs.server']
1405 server_and_port = pylonsapp.config['vcs.server']
1409 protocol = pylonsapp.config['vcs.server.protocol']
1406 protocol = pylonsapp.config['vcs.server.protocol']
1410 server = create_vcsserver_proxy(server_and_port, protocol)
1407 server = create_vcsserver_proxy(server_and_port, protocol)
1411 with server:
1408 with server:
1412 vcs_pid = server.get_pid()
1409 vcs_pid = server.get_pid()
1413 server.run_gc()
1410 server.run_gc()
1414 vcs_process = psutil.Process(vcs_pid)
1411 vcs_process = psutil.Process(vcs_pid)
1415 mem = vcs_process.memory_info()
1412 mem = vcs_process.memory_info()
1416 client.tag_before('vcsserver.rss', mem.rss)
1413 client.tag_before('vcsserver.rss', mem.rss)
1417 client.tag_before('vcsserver.vms', mem.vms)
1414 client.tag_before('vcsserver.vms', mem.vms)
1418
1415
1419 test_process = psutil.Process()
1416 test_process = psutil.Process()
1420 mem = test_process.memory_info()
1417 mem = test_process.memory_info()
1421 client.tag_before('test.rss', mem.rss)
1418 client.tag_before('test.rss', mem.rss)
1422 client.tag_before('test.vms', mem.vms)
1419 client.tag_before('test.vms', mem.vms)
1423
1420
1424 client.tag_before('time', time.time())
1421 client.tag_before('time', time.time())
1425
1422
1426 @request.addfinalizer
1423 @request.addfinalizer
1427 def send_stats():
1424 def send_stats():
1428 client.tag_after('time', time.time())
1425 client.tag_after('time', time.time())
1429 with server:
1426 with server:
1430 gc_stats = server.run_gc()
1427 gc_stats = server.run_gc()
1431 for tag, value in gc_stats.items():
1428 for tag, value in gc_stats.items():
1432 client.tag_after(tag, value)
1429 client.tag_after(tag, value)
1433 mem = vcs_process.memory_info()
1430 mem = vcs_process.memory_info()
1434 client.tag_after('vcsserver.rss', mem.rss)
1431 client.tag_after('vcsserver.rss', mem.rss)
1435 client.tag_after('vcsserver.vms', mem.vms)
1432 client.tag_after('vcsserver.vms', mem.vms)
1436
1433
1437 mem = test_process.memory_info()
1434 mem = test_process.memory_info()
1438 client.tag_after('test.rss', mem.rss)
1435 client.tag_after('test.rss', mem.rss)
1439 client.tag_after('test.vms', mem.vms)
1436 client.tag_after('test.vms', mem.vms)
1440
1437
1441 client.collect({
1438 client.collect({
1442 'message': "Finished",
1439 'message': "Finished",
1443 })
1440 })
1444 client.send_stats()
1441 client.send_stats()
1445
1442
1446 return client
1443 return client
1447
1444
1448
1445
1449 class AppenlightClient():
1446 class AppenlightClient():
1450
1447
1451 url_template = '{url}?protocol_version=0.5'
1448 url_template = '{url}?protocol_version=0.5'
1452
1449
1453 def __init__(
1450 def __init__(
1454 self, url, api_key, add_server=True, add_timestamp=True,
1451 self, url, api_key, add_server=True, add_timestamp=True,
1455 namespace=None, request=None, testrun=None):
1452 namespace=None, request=None, testrun=None):
1456 self.url = self.url_template.format(url=url)
1453 self.url = self.url_template.format(url=url)
1457 self.api_key = api_key
1454 self.api_key = api_key
1458 self.add_server = add_server
1455 self.add_server = add_server
1459 self.add_timestamp = add_timestamp
1456 self.add_timestamp = add_timestamp
1460 self.namespace = namespace
1457 self.namespace = namespace
1461 self.request = request
1458 self.request = request
1462 self.server = socket.getfqdn(socket.gethostname())
1459 self.server = socket.getfqdn(socket.gethostname())
1463 self.tags_before = {}
1460 self.tags_before = {}
1464 self.tags_after = {}
1461 self.tags_after = {}
1465 self.stats = []
1462 self.stats = []
1466 self.testrun = testrun or {}
1463 self.testrun = testrun or {}
1467
1464
1468 def tag_before(self, tag, value):
1465 def tag_before(self, tag, value):
1469 self.tags_before[tag] = value
1466 self.tags_before[tag] = value
1470
1467
1471 def tag_after(self, tag, value):
1468 def tag_after(self, tag, value):
1472 self.tags_after[tag] = value
1469 self.tags_after[tag] = value
1473
1470
1474 def collect(self, data):
1471 def collect(self, data):
1475 if self.add_server:
1472 if self.add_server:
1476 data.setdefault('server', self.server)
1473 data.setdefault('server', self.server)
1477 if self.add_timestamp:
1474 if self.add_timestamp:
1478 data.setdefault('date', datetime.datetime.utcnow().isoformat())
1475 data.setdefault('date', datetime.datetime.utcnow().isoformat())
1479 if self.namespace:
1476 if self.namespace:
1480 data.setdefault('namespace', self.namespace)
1477 data.setdefault('namespace', self.namespace)
1481 if self.request:
1478 if self.request:
1482 data.setdefault('request', self.request)
1479 data.setdefault('request', self.request)
1483 self.stats.append(data)
1480 self.stats.append(data)
1484
1481
1485 def send_stats(self):
1482 def send_stats(self):
1486 tags = [
1483 tags = [
1487 ('testrun', self.request),
1484 ('testrun', self.request),
1488 ('testrun.start', self.testrun['start']),
1485 ('testrun.start', self.testrun['start']),
1489 ('testrun.timestamp', self.testrun['timestamp']),
1486 ('testrun.timestamp', self.testrun['timestamp']),
1490 ('test', self.namespace),
1487 ('test', self.namespace),
1491 ]
1488 ]
1492 for key, value in self.tags_before.items():
1489 for key, value in self.tags_before.items():
1493 tags.append((key + '.before', value))
1490 tags.append((key + '.before', value))
1494 try:
1491 try:
1495 delta = self.tags_after[key] - value
1492 delta = self.tags_after[key] - value
1496 tags.append((key + '.delta', delta))
1493 tags.append((key + '.delta', delta))
1497 except Exception:
1494 except Exception:
1498 pass
1495 pass
1499 for key, value in self.tags_after.items():
1496 for key, value in self.tags_after.items():
1500 tags.append((key + '.after', value))
1497 tags.append((key + '.after', value))
1501 self.collect({
1498 self.collect({
1502 'message': "Collected tags",
1499 'message': "Collected tags",
1503 'tags': tags,
1500 'tags': tags,
1504 })
1501 })
1505
1502
1506 response = requests.post(
1503 response = requests.post(
1507 self.url,
1504 self.url,
1508 headers={
1505 headers={
1509 'X-appenlight-api-key': self.api_key},
1506 'X-appenlight-api-key': self.api_key},
1510 json=self.stats,
1507 json=self.stats,
1511 )
1508 )
1512
1509
1513 if not response.status_code == 200:
1510 if not response.status_code == 200:
1514 pprint.pprint(self.stats)
1511 pprint.pprint(self.stats)
1515 print response.headers
1512 print response.headers
1516 print response.text
1513 print response.text
1517 raise Exception('Sending to appenlight failed')
1514 raise Exception('Sending to appenlight failed')
1518
1515
1519
1516
1520 @pytest.fixture
1517 @pytest.fixture
1521 def gist_util(request, pylonsapp):
1518 def gist_util(request, pylonsapp):
1522 """
1519 """
1523 Provides a wired instance of `GistUtility` with integrated cleanup.
1520 Provides a wired instance of `GistUtility` with integrated cleanup.
1524 """
1521 """
1525 utility = GistUtility()
1522 utility = GistUtility()
1526 request.addfinalizer(utility.cleanup)
1523 request.addfinalizer(utility.cleanup)
1527 return utility
1524 return utility
1528
1525
1529
1526
1530 class GistUtility(object):
1527 class GistUtility(object):
1531 def __init__(self):
1528 def __init__(self):
1532 self.fixture = Fixture()
1529 self.fixture = Fixture()
1533 self.gist_ids = []
1530 self.gist_ids = []
1534
1531
1535 def create_gist(self, **kwargs):
1532 def create_gist(self, **kwargs):
1536 gist = self.fixture.create_gist(**kwargs)
1533 gist = self.fixture.create_gist(**kwargs)
1537 self.gist_ids.append(gist.gist_id)
1534 self.gist_ids.append(gist.gist_id)
1538 return gist
1535 return gist
1539
1536
1540 def cleanup(self):
1537 def cleanup(self):
1541 for id_ in self.gist_ids:
1538 for id_ in self.gist_ids:
1542 self.fixture.destroy_gists(str(id_))
1539 self.fixture.destroy_gists(str(id_))
1543
1540
1544
1541
1545 @pytest.fixture
1542 @pytest.fixture
1546 def enabled_backends(request):
1543 def enabled_backends(request):
1547 backends = request.config.option.backends
1544 backends = request.config.option.backends
1548 return backends[:]
1545 return backends[:]
1549
1546
1550
1547
1551 @pytest.fixture
1548 @pytest.fixture
1552 def settings_util(request):
1549 def settings_util(request):
1553 """
1550 """
1554 Provides a wired instance of `SettingsUtility` with integrated cleanup.
1551 Provides a wired instance of `SettingsUtility` with integrated cleanup.
1555 """
1552 """
1556 utility = SettingsUtility()
1553 utility = SettingsUtility()
1557 request.addfinalizer(utility.cleanup)
1554 request.addfinalizer(utility.cleanup)
1558 return utility
1555 return utility
1559
1556
1560
1557
1561 class SettingsUtility(object):
1558 class SettingsUtility(object):
1562 def __init__(self):
1559 def __init__(self):
1563 self.rhodecode_ui_ids = []
1560 self.rhodecode_ui_ids = []
1564 self.rhodecode_setting_ids = []
1561 self.rhodecode_setting_ids = []
1565 self.repo_rhodecode_ui_ids = []
1562 self.repo_rhodecode_ui_ids = []
1566 self.repo_rhodecode_setting_ids = []
1563 self.repo_rhodecode_setting_ids = []
1567
1564
1568 def create_repo_rhodecode_ui(
1565 def create_repo_rhodecode_ui(
1569 self, repo, section, value, key=None, active=True, cleanup=True):
1566 self, repo, section, value, key=None, active=True, cleanup=True):
1570 key = key or hashlib.sha1(
1567 key = key or hashlib.sha1(
1571 '{}{}{}'.format(section, value, repo.repo_id)).hexdigest()
1568 '{}{}{}'.format(section, value, repo.repo_id)).hexdigest()
1572
1569
1573 setting = RepoRhodeCodeUi()
1570 setting = RepoRhodeCodeUi()
1574 setting.repository_id = repo.repo_id
1571 setting.repository_id = repo.repo_id
1575 setting.ui_section = section
1572 setting.ui_section = section
1576 setting.ui_value = value
1573 setting.ui_value = value
1577 setting.ui_key = key
1574 setting.ui_key = key
1578 setting.ui_active = active
1575 setting.ui_active = active
1579 Session().add(setting)
1576 Session().add(setting)
1580 Session().commit()
1577 Session().commit()
1581
1578
1582 if cleanup:
1579 if cleanup:
1583 self.repo_rhodecode_ui_ids.append(setting.ui_id)
1580 self.repo_rhodecode_ui_ids.append(setting.ui_id)
1584 return setting
1581 return setting
1585
1582
1586 def create_rhodecode_ui(
1583 def create_rhodecode_ui(
1587 self, section, value, key=None, active=True, cleanup=True):
1584 self, section, value, key=None, active=True, cleanup=True):
1588 key = key or hashlib.sha1('{}{}'.format(section, value)).hexdigest()
1585 key = key or hashlib.sha1('{}{}'.format(section, value)).hexdigest()
1589
1586
1590 setting = RhodeCodeUi()
1587 setting = RhodeCodeUi()
1591 setting.ui_section = section
1588 setting.ui_section = section
1592 setting.ui_value = value
1589 setting.ui_value = value
1593 setting.ui_key = key
1590 setting.ui_key = key
1594 setting.ui_active = active
1591 setting.ui_active = active
1595 Session().add(setting)
1592 Session().add(setting)
1596 Session().commit()
1593 Session().commit()
1597
1594
1598 if cleanup:
1595 if cleanup:
1599 self.rhodecode_ui_ids.append(setting.ui_id)
1596 self.rhodecode_ui_ids.append(setting.ui_id)
1600 return setting
1597 return setting
1601
1598
1602 def create_repo_rhodecode_setting(
1599 def create_repo_rhodecode_setting(
1603 self, repo, name, value, type_, cleanup=True):
1600 self, repo, name, value, type_, cleanup=True):
1604 setting = RepoRhodeCodeSetting(
1601 setting = RepoRhodeCodeSetting(
1605 repo.repo_id, key=name, val=value, type=type_)
1602 repo.repo_id, key=name, val=value, type=type_)
1606 Session().add(setting)
1603 Session().add(setting)
1607 Session().commit()
1604 Session().commit()
1608
1605
1609 if cleanup:
1606 if cleanup:
1610 self.repo_rhodecode_setting_ids.append(setting.app_settings_id)
1607 self.repo_rhodecode_setting_ids.append(setting.app_settings_id)
1611 return setting
1608 return setting
1612
1609
1613 def create_rhodecode_setting(self, name, value, type_, cleanup=True):
1610 def create_rhodecode_setting(self, name, value, type_, cleanup=True):
1614 setting = RhodeCodeSetting(key=name, val=value, type=type_)
1611 setting = RhodeCodeSetting(key=name, val=value, type=type_)
1615 Session().add(setting)
1612 Session().add(setting)
1616 Session().commit()
1613 Session().commit()
1617
1614
1618 if cleanup:
1615 if cleanup:
1619 self.rhodecode_setting_ids.append(setting.app_settings_id)
1616 self.rhodecode_setting_ids.append(setting.app_settings_id)
1620
1617
1621 return setting
1618 return setting
1622
1619
1623 def cleanup(self):
1620 def cleanup(self):
1624 for id_ in self.rhodecode_ui_ids:
1621 for id_ in self.rhodecode_ui_ids:
1625 setting = RhodeCodeUi.get(id_)
1622 setting = RhodeCodeUi.get(id_)
1626 Session().delete(setting)
1623 Session().delete(setting)
1627
1624
1628 for id_ in self.rhodecode_setting_ids:
1625 for id_ in self.rhodecode_setting_ids:
1629 setting = RhodeCodeSetting.get(id_)
1626 setting = RhodeCodeSetting.get(id_)
1630 Session().delete(setting)
1627 Session().delete(setting)
1631
1628
1632 for id_ in self.repo_rhodecode_ui_ids:
1629 for id_ in self.repo_rhodecode_ui_ids:
1633 setting = RepoRhodeCodeUi.get(id_)
1630 setting = RepoRhodeCodeUi.get(id_)
1634 Session().delete(setting)
1631 Session().delete(setting)
1635
1632
1636 for id_ in self.repo_rhodecode_setting_ids:
1633 for id_ in self.repo_rhodecode_setting_ids:
1637 setting = RepoRhodeCodeSetting.get(id_)
1634 setting = RepoRhodeCodeSetting.get(id_)
1638 Session().delete(setting)
1635 Session().delete(setting)
1639
1636
1640 Session().commit()
1637 Session().commit()
1641
1638
1642
1639
1643 @pytest.fixture
1640 @pytest.fixture
1644 def no_notifications(request):
1641 def no_notifications(request):
1645 notification_patcher = mock.patch(
1642 notification_patcher = mock.patch(
1646 'rhodecode.model.notification.NotificationModel.create')
1643 'rhodecode.model.notification.NotificationModel.create')
1647 notification_patcher.start()
1644 notification_patcher.start()
1648 request.addfinalizer(notification_patcher.stop)
1645 request.addfinalizer(notification_patcher.stop)
1649
1646
1650
1647
1651 @pytest.fixture(scope='session')
1648 @pytest.fixture(scope='session')
1652 def repeat(request):
1649 def repeat(request):
1653 """
1650 """
1654 The number of repetitions is based on this fixture.
1651 The number of repetitions is based on this fixture.
1655
1652
1656 Slower calls may divide it by 10 or 100. It is chosen in a way so that the
1653 Slower calls may divide it by 10 or 100. It is chosen in a way so that the
1657 tests are not too slow in our default test suite.
1654 tests are not too slow in our default test suite.
1658 """
1655 """
1659 return request.config.getoption('--repeat')
1656 return request.config.getoption('--repeat')
1660
1657
1661
1658
1662 @pytest.fixture
1659 @pytest.fixture
1663 def rhodecode_fixtures():
1660 def rhodecode_fixtures():
1664 return Fixture()
1661 return Fixture()
1665
1662
1666
1663
1667 @pytest.fixture
1664 @pytest.fixture
1668 def context_stub():
1665 def context_stub():
1669 """
1666 """
1670 Stub context object.
1667 Stub context object.
1671 """
1668 """
1672 context = pyramid.testing.DummyResource()
1669 context = pyramid.testing.DummyResource()
1673 return context
1670 return context
1674
1671
1675
1672
1676 @pytest.fixture
1673 @pytest.fixture
1677 def request_stub():
1674 def request_stub():
1678 """
1675 """
1679 Stub request object.
1676 Stub request object.
1680 """
1677 """
1681 from rhodecode.lib.base import bootstrap_request
1678 from rhodecode.lib.base import bootstrap_request
1682 request = bootstrap_request(scheme='https')
1679 request = bootstrap_request(scheme='https')
1683 return request
1680 return request
1684
1681
1685
1682
1686 @pytest.fixture
1683 @pytest.fixture
1687 def config_stub(request, request_stub):
1684 def config_stub(request, request_stub):
1688 """
1685 """
1689 Set up pyramid.testing and return the Configurator.
1686 Set up pyramid.testing and return the Configurator.
1690 """
1687 """
1691 from rhodecode.lib.base import bootstrap_config
1688 from rhodecode.lib.base import bootstrap_config
1692 config = bootstrap_config(request=request_stub)
1689 config = bootstrap_config(request=request_stub)
1693
1690
1694 @request.addfinalizer
1691 @request.addfinalizer
1695 def cleanup():
1692 def cleanup():
1696 pyramid.testing.tearDown()
1693 pyramid.testing.tearDown()
1697
1694
1698 return config
1695 return config
1699
1696
1700
1697
1701 @pytest.fixture
1698 @pytest.fixture
1702 def StubIntegrationType():
1699 def StubIntegrationType():
1703 class _StubIntegrationType(IntegrationTypeBase):
1700 class _StubIntegrationType(IntegrationTypeBase):
1704 """ Test integration type class """
1701 """ Test integration type class """
1705
1702
1706 key = 'test'
1703 key = 'test'
1707 display_name = 'Test integration type'
1704 display_name = 'Test integration type'
1708 description = 'A test integration type for testing'
1705 description = 'A test integration type for testing'
1709 icon = 'test_icon_html_image'
1706 icon = 'test_icon_html_image'
1710
1707
1711 def __init__(self, settings):
1708 def __init__(self, settings):
1712 super(_StubIntegrationType, self).__init__(settings)
1709 super(_StubIntegrationType, self).__init__(settings)
1713 self.sent_events = [] # for testing
1710 self.sent_events = [] # for testing
1714
1711
1715 def send_event(self, event):
1712 def send_event(self, event):
1716 self.sent_events.append(event)
1713 self.sent_events.append(event)
1717
1714
1718 def settings_schema(self):
1715 def settings_schema(self):
1719 class SettingsSchema(colander.Schema):
1716 class SettingsSchema(colander.Schema):
1720 test_string_field = colander.SchemaNode(
1717 test_string_field = colander.SchemaNode(
1721 colander.String(),
1718 colander.String(),
1722 missing=colander.required,
1719 missing=colander.required,
1723 title='test string field',
1720 title='test string field',
1724 )
1721 )
1725 test_int_field = colander.SchemaNode(
1722 test_int_field = colander.SchemaNode(
1726 colander.Int(),
1723 colander.Int(),
1727 title='some integer setting',
1724 title='some integer setting',
1728 )
1725 )
1729 return SettingsSchema()
1726 return SettingsSchema()
1730
1727
1731
1728
1732 integration_type_registry.register_integration_type(_StubIntegrationType)
1729 integration_type_registry.register_integration_type(_StubIntegrationType)
1733 return _StubIntegrationType
1730 return _StubIntegrationType
1734
1731
1735 @pytest.fixture
1732 @pytest.fixture
1736 def stub_integration_settings():
1733 def stub_integration_settings():
1737 return {
1734 return {
1738 'test_string_field': 'some data',
1735 'test_string_field': 'some data',
1739 'test_int_field': 100,
1736 'test_int_field': 100,
1740 }
1737 }
1741
1738
1742
1739
1743 @pytest.fixture
1740 @pytest.fixture
1744 def repo_integration_stub(request, repo_stub, StubIntegrationType,
1741 def repo_integration_stub(request, repo_stub, StubIntegrationType,
1745 stub_integration_settings):
1742 stub_integration_settings):
1746 integration = IntegrationModel().create(
1743 integration = IntegrationModel().create(
1747 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1744 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1748 name='test repo integration',
1745 name='test repo integration',
1749 repo=repo_stub, repo_group=None, child_repos_only=None)
1746 repo=repo_stub, repo_group=None, child_repos_only=None)
1750
1747
1751 @request.addfinalizer
1748 @request.addfinalizer
1752 def cleanup():
1749 def cleanup():
1753 IntegrationModel().delete(integration)
1750 IntegrationModel().delete(integration)
1754
1751
1755 return integration
1752 return integration
1756
1753
1757
1754
1758 @pytest.fixture
1755 @pytest.fixture
1759 def repogroup_integration_stub(request, test_repo_group, StubIntegrationType,
1756 def repogroup_integration_stub(request, test_repo_group, StubIntegrationType,
1760 stub_integration_settings):
1757 stub_integration_settings):
1761 integration = IntegrationModel().create(
1758 integration = IntegrationModel().create(
1762 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1759 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1763 name='test repogroup integration',
1760 name='test repogroup integration',
1764 repo=None, repo_group=test_repo_group, child_repos_only=True)
1761 repo=None, repo_group=test_repo_group, child_repos_only=True)
1765
1762
1766 @request.addfinalizer
1763 @request.addfinalizer
1767 def cleanup():
1764 def cleanup():
1768 IntegrationModel().delete(integration)
1765 IntegrationModel().delete(integration)
1769
1766
1770 return integration
1767 return integration
1771
1768
1772
1769
1773 @pytest.fixture
1770 @pytest.fixture
1774 def repogroup_recursive_integration_stub(request, test_repo_group,
1771 def repogroup_recursive_integration_stub(request, test_repo_group,
1775 StubIntegrationType, stub_integration_settings):
1772 StubIntegrationType, stub_integration_settings):
1776 integration = IntegrationModel().create(
1773 integration = IntegrationModel().create(
1777 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1774 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1778 name='test recursive repogroup integration',
1775 name='test recursive repogroup integration',
1779 repo=None, repo_group=test_repo_group, child_repos_only=False)
1776 repo=None, repo_group=test_repo_group, child_repos_only=False)
1780
1777
1781 @request.addfinalizer
1778 @request.addfinalizer
1782 def cleanup():
1779 def cleanup():
1783 IntegrationModel().delete(integration)
1780 IntegrationModel().delete(integration)
1784
1781
1785 return integration
1782 return integration
1786
1783
1787
1784
1788 @pytest.fixture
1785 @pytest.fixture
1789 def global_integration_stub(request, StubIntegrationType,
1786 def global_integration_stub(request, StubIntegrationType,
1790 stub_integration_settings):
1787 stub_integration_settings):
1791 integration = IntegrationModel().create(
1788 integration = IntegrationModel().create(
1792 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1789 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1793 name='test global integration',
1790 name='test global integration',
1794 repo=None, repo_group=None, child_repos_only=None)
1791 repo=None, repo_group=None, child_repos_only=None)
1795
1792
1796 @request.addfinalizer
1793 @request.addfinalizer
1797 def cleanup():
1794 def cleanup():
1798 IntegrationModel().delete(integration)
1795 IntegrationModel().delete(integration)
1799
1796
1800 return integration
1797 return integration
1801
1798
1802
1799
1803 @pytest.fixture
1800 @pytest.fixture
1804 def root_repos_integration_stub(request, StubIntegrationType,
1801 def root_repos_integration_stub(request, StubIntegrationType,
1805 stub_integration_settings):
1802 stub_integration_settings):
1806 integration = IntegrationModel().create(
1803 integration = IntegrationModel().create(
1807 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1804 StubIntegrationType, settings=stub_integration_settings, enabled=True,
1808 name='test global integration',
1805 name='test global integration',
1809 repo=None, repo_group=None, child_repos_only=True)
1806 repo=None, repo_group=None, child_repos_only=True)
1810
1807
1811 @request.addfinalizer
1808 @request.addfinalizer
1812 def cleanup():
1809 def cleanup():
1813 IntegrationModel().delete(integration)
1810 IntegrationModel().delete(integration)
1814
1811
1815 return integration
1812 return integration
1816
1813
1817
1814
1818 @pytest.fixture
1815 @pytest.fixture
1819 def local_dt_to_utc():
1816 def local_dt_to_utc():
1820 def _factory(dt):
1817 def _factory(dt):
1821 return dt.replace(tzinfo=dateutil.tz.tzlocal()).astimezone(
1818 return dt.replace(tzinfo=dateutil.tz.tzlocal()).astimezone(
1822 dateutil.tz.tzutc()).replace(tzinfo=None)
1819 dateutil.tz.tzutc()).replace(tzinfo=None)
1823 return _factory
1820 return _factory
1824
1821
1825
1822
1826 @pytest.fixture
1823 @pytest.fixture
1827 def disable_anonymous_user(request, pylonsapp):
1824 def disable_anonymous_user(request, pylonsapp):
1828 set_anonymous_access(False)
1825 set_anonymous_access(False)
1829
1826
1830 @request.addfinalizer
1827 @request.addfinalizer
1831 def cleanup():
1828 def cleanup():
1832 set_anonymous_access(True)
1829 set_anonymous_access(True)
1833
1830
1834
1831
1835 @pytest.fixture
1832 @pytest.fixture
1836 def rc_fixture(request):
1833 def rc_fixture(request):
1837 return Fixture()
1834 return Fixture()
1838
1835
1839
1836
1840 @pytest.fixture
1837 @pytest.fixture
1841 def repo_groups(request):
1838 def repo_groups(request):
1842 fixture = Fixture()
1839 fixture = Fixture()
1843
1840
1844 session = Session()
1841 session = Session()
1845 zombie_group = fixture.create_repo_group('zombie')
1842 zombie_group = fixture.create_repo_group('zombie')
1846 parent_group = fixture.create_repo_group('parent')
1843 parent_group = fixture.create_repo_group('parent')
1847 child_group = fixture.create_repo_group('parent/child')
1844 child_group = fixture.create_repo_group('parent/child')
1848 groups_in_db = session.query(RepoGroup).all()
1845 groups_in_db = session.query(RepoGroup).all()
1849 assert len(groups_in_db) == 3
1846 assert len(groups_in_db) == 3
1850 assert child_group.group_parent_id == parent_group.group_id
1847 assert child_group.group_parent_id == parent_group.group_id
1851
1848
1852 @request.addfinalizer
1849 @request.addfinalizer
1853 def cleanup():
1850 def cleanup():
1854 fixture.destroy_repo_group(zombie_group)
1851 fixture.destroy_repo_group(zombie_group)
1855 fixture.destroy_repo_group(child_group)
1852 fixture.destroy_repo_group(child_group)
1856 fixture.destroy_repo_group(parent_group)
1853 fixture.destroy_repo_group(parent_group)
1857
1854
1858 return zombie_group, parent_group, child_group
1855 return zombie_group, parent_group, child_group
General Comments 0
You need to be logged in to leave comments. Login now