##// END OF EJS Templates
tests: write proper bytes for test ini
super-admin -
r4992:07e90fe6 default
parent child Browse files
Show More
@@ -1,345 +1,346 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
3 # Copyright (C) 2010-2020 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 """
21 """
22 py.test config for test suite for making push/pull operations.
22 py.test config for test suite for making push/pull operations.
23
23
24 .. important::
24 .. important::
25
25
26 You must have git >= 1.8.5 for tests to work fine. With 68b939b git started
26 You must have git >= 1.8.5 for tests to work fine. With 68b939b git started
27 to redirect things to stderr instead of stdout.
27 to redirect things to stderr instead of stdout.
28 """
28 """
29
29
30 import os
30 import os
31 import tempfile
31 import tempfile
32 import textwrap
32 import textwrap
33 import pytest
33 import pytest
34 import logging
34 import logging
35
35
36 from rhodecode import events
36 from rhodecode import events
37 from rhodecode.lib.str_utils import safe_bytes
37 from rhodecode.model.db import Integration, UserRepoToPerm, Permission, \
38 from rhodecode.model.db import Integration, UserRepoToPerm, Permission, \
38 UserToRepoBranchPermission, User
39 UserToRepoBranchPermission, User
39 from rhodecode.model.integration import IntegrationModel
40 from rhodecode.model.integration import IntegrationModel
40 from rhodecode.model.db import Repository
41 from rhodecode.model.db import Repository
41 from rhodecode.model.meta import Session
42 from rhodecode.model.meta import Session
42 from rhodecode.model.settings import SettingsModel
43 from rhodecode.model.settings import SettingsModel
43 from rhodecode.integrations.types.webhook import WebhookIntegrationType
44 from rhodecode.integrations.types.webhook import WebhookIntegrationType
44
45
45 from rhodecode.tests import GIT_REPO, HG_REPO
46 from rhodecode.tests import GIT_REPO, HG_REPO
46 from rhodecode.tests.fixture import Fixture
47 from rhodecode.tests.fixture import Fixture
47 from rhodecode.tests.server_utils import RcWebServer
48 from rhodecode.tests.server_utils import RcWebServer
48
49
49 REPO_GROUP = 'a_repo_group'
50 REPO_GROUP = 'a_repo_group'
50 HG_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, HG_REPO)
51 HG_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, HG_REPO)
51 GIT_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, GIT_REPO)
52 GIT_REPO_WITH_GROUP = '%s/%s' % (REPO_GROUP, GIT_REPO)
52
53
53 log = logging.getLogger(__name__)
54 log = logging.getLogger(__name__)
54
55
55
56
56 @pytest.fixture(scope="module")
57 @pytest.fixture(scope="module")
57 def rcextensions(request, db_connection, tmpdir_factory):
58 def rcextensions(request, db_connection, tmpdir_factory):
58 """
59 """
59 Installs a testing rcextensions pack to ensure they work as expected.
60 Installs a testing rcextensions pack to ensure they work as expected.
60 """
61 """
61 init_content = textwrap.dedent("""
62 init_content = textwrap.dedent("""
62 # Forward import the example rcextensions to make it
63 # Forward import the example rcextensions to make it
63 # active for our tests.
64 # active for our tests.
64 from rhodecode.tests.other.example_rcextensions import *
65 from rhodecode.tests.other.example_rcextensions import *
65 """)
66 """)
66
67
67 # Note: rcextensions are looked up based on the path of the ini file
68 # Note: rcextensions are looked up based on the path of the ini file
68 root_path = tmpdir_factory.getbasetemp()
69 root_path = tmpdir_factory.getbasetemp()
69 rcextensions_path = root_path.join('rcextensions')
70 rcextensions_path = root_path.join('rcextensions')
70 init_path = rcextensions_path.join('__init__.py')
71 init_path = rcextensions_path.join('__init__.py')
71
72
72 if rcextensions_path.check():
73 if rcextensions_path.check():
73 pytest.fail(
74 pytest.fail(
74 "Path for rcextensions already exists, please clean up before "
75 "Path for rcextensions already exists, please clean up before "
75 "test run this path: %s" % (rcextensions_path, ))
76 "test run this path: %s" % (rcextensions_path, ))
76 return
77 return
77
78
78 request.addfinalizer(rcextensions_path.remove)
79 request.addfinalizer(rcextensions_path.remove)
79 init_path.write_binary(init_content, ensure=True)
80 init_path.write_binary(safe_bytes(init_content), ensure=True)
80
81
81
82
82 @pytest.fixture(scope="module")
83 @pytest.fixture(scope="module")
83 def repos(request, db_connection):
84 def repos(request, db_connection):
84 """Create a copy of each test repo in a repo group."""
85 """Create a copy of each test repo in a repo group."""
85 fixture = Fixture()
86 fixture = Fixture()
86 repo_group = fixture.create_repo_group(REPO_GROUP)
87 repo_group = fixture.create_repo_group(REPO_GROUP)
87 repo_group_id = repo_group.group_id
88 repo_group_id = repo_group.group_id
88 fixture.create_fork(HG_REPO, HG_REPO,
89 fixture.create_fork(HG_REPO, HG_REPO,
89 repo_name_full=HG_REPO_WITH_GROUP,
90 repo_name_full=HG_REPO_WITH_GROUP,
90 repo_group=repo_group_id)
91 repo_group=repo_group_id)
91 fixture.create_fork(GIT_REPO, GIT_REPO,
92 fixture.create_fork(GIT_REPO, GIT_REPO,
92 repo_name_full=GIT_REPO_WITH_GROUP,
93 repo_name_full=GIT_REPO_WITH_GROUP,
93 repo_group=repo_group_id)
94 repo_group=repo_group_id)
94
95
95 @request.addfinalizer
96 @request.addfinalizer
96 def cleanup():
97 def cleanup():
97 fixture.destroy_repo(HG_REPO_WITH_GROUP)
98 fixture.destroy_repo(HG_REPO_WITH_GROUP)
98 fixture.destroy_repo(GIT_REPO_WITH_GROUP)
99 fixture.destroy_repo(GIT_REPO_WITH_GROUP)
99 fixture.destroy_repo_group(repo_group_id)
100 fixture.destroy_repo_group(repo_group_id)
100
101
101
102
102 @pytest.fixture(scope="module")
103 @pytest.fixture(scope="module")
103 def rc_web_server_config_modification():
104 def rc_web_server_config_modification():
104 return []
105 return []
105
106
106
107
107 @pytest.fixture(scope="module")
108 @pytest.fixture(scope="module")
108 def rc_web_server_config_factory(testini_factory, rc_web_server_config_modification):
109 def rc_web_server_config_factory(testini_factory, rc_web_server_config_modification):
109 """
110 """
110 Configuration file used for the fixture `rc_web_server`.
111 Configuration file used for the fixture `rc_web_server`.
111 """
112 """
112
113
113 def factory(rcweb_port, vcsserver_port):
114 def factory(rcweb_port, vcsserver_port):
114 custom_params = [
115 custom_params = [
115 {'handler_console': {'level': 'DEBUG'}},
116 {'handler_console': {'level': 'DEBUG'}},
116 {'server:main': {'port': rcweb_port}},
117 {'server:main': {'port': rcweb_port}},
117 {'app:main': {'vcs.server': 'localhost:%s' % vcsserver_port}}
118 {'app:main': {'vcs.server': 'localhost:%s' % vcsserver_port}}
118 ]
119 ]
119 custom_params.extend(rc_web_server_config_modification)
120 custom_params.extend(rc_web_server_config_modification)
120 return testini_factory(custom_params)
121 return testini_factory(custom_params)
121 return factory
122 return factory
122
123
123
124
124 @pytest.fixture(scope="module")
125 @pytest.fixture(scope="module")
125 def rc_web_server(
126 def rc_web_server(
126 request, vcsserver_factory, available_port_factory,
127 request, vcsserver_factory, available_port_factory,
127 rc_web_server_config_factory, repos, rcextensions):
128 rc_web_server_config_factory, repos, rcextensions):
128 """
129 """
129 Run the web server as a subprocess. with it's own instance of vcsserver
130 Run the web server as a subprocess. with it's own instance of vcsserver
130 """
131 """
131 rcweb_port = available_port_factory()
132 rcweb_port = available_port_factory()
132 log.info('Using rcweb ops test port {}'.format(rcweb_port))
133 log.info('Using rcweb ops test port {}'.format(rcweb_port))
133
134
134 vcsserver_port = available_port_factory()
135 vcsserver_port = available_port_factory()
135 log.info('Using vcsserver ops test port {}'.format(vcsserver_port))
136 log.info('Using vcsserver ops test port {}'.format(vcsserver_port))
136
137
137 vcs_log = os.path.join(tempfile.gettempdir(), 'rc_op_vcs.log')
138 vcs_log = os.path.join(tempfile.gettempdir(), 'rc_op_vcs.log')
138 vcsserver_factory(
139 vcsserver_factory(
139 request, vcsserver_port=vcsserver_port,
140 request, vcsserver_port=vcsserver_port,
140 log_file=vcs_log,
141 log_file=vcs_log,
141 overrides=(
142 overrides=(
142 {'server:main': {'workers': 2}},
143 {'server:main': {'workers': 2}},
143 {'server:main': {'graceful_timeout': 10}},
144 {'server:main': {'graceful_timeout': 10}},
144 ))
145 ))
145
146
146 rc_log = os.path.join(tempfile.gettempdir(), 'rc_op_web.log')
147 rc_log = os.path.join(tempfile.gettempdir(), 'rc_op_web.log')
147 rc_web_server_config = rc_web_server_config_factory(
148 rc_web_server_config = rc_web_server_config_factory(
148 rcweb_port=rcweb_port,
149 rcweb_port=rcweb_port,
149 vcsserver_port=vcsserver_port)
150 vcsserver_port=vcsserver_port)
150 server = RcWebServer(rc_web_server_config, log_file=rc_log)
151 server = RcWebServer(rc_web_server_config, log_file=rc_log)
151 server.start()
152 server.start()
152
153
153 @request.addfinalizer
154 @request.addfinalizer
154 def cleanup():
155 def cleanup():
155 server.shutdown()
156 server.shutdown()
156
157
157 server.wait_until_ready()
158 server.wait_until_ready()
158 return server
159 return server
159
160
160
161
161 @pytest.fixture()
162 @pytest.fixture()
162 def disable_locking(baseapp):
163 def disable_locking(baseapp):
163 r = Repository.get_by_repo_name(GIT_REPO)
164 r = Repository.get_by_repo_name(GIT_REPO)
164 Repository.unlock(r)
165 Repository.unlock(r)
165 r.enable_locking = False
166 r.enable_locking = False
166 Session().add(r)
167 Session().add(r)
167 Session().commit()
168 Session().commit()
168
169
169 r = Repository.get_by_repo_name(HG_REPO)
170 r = Repository.get_by_repo_name(HG_REPO)
170 Repository.unlock(r)
171 Repository.unlock(r)
171 r.enable_locking = False
172 r.enable_locking = False
172 Session().add(r)
173 Session().add(r)
173 Session().commit()
174 Session().commit()
174
175
175
176
176 @pytest.fixture()
177 @pytest.fixture()
177 def enable_auth_plugins(request, baseapp, csrf_token):
178 def enable_auth_plugins(request, baseapp, csrf_token):
178 """
179 """
179 Return a factory object that when called, allows to control which
180 Return a factory object that when called, allows to control which
180 authentication plugins are enabled.
181 authentication plugins are enabled.
181 """
182 """
182 def _enable_plugins(plugins_list, override=None):
183 def _enable_plugins(plugins_list, override=None):
183 override = override or {}
184 override = override or {}
184 params = {
185 params = {
185 'auth_plugins': ','.join(plugins_list),
186 'auth_plugins': ','.join(plugins_list),
186 }
187 }
187
188
188 # helper translate some names to others
189 # helper translate some names to others
189 name_map = {
190 name_map = {
190 'token': 'authtoken'
191 'token': 'authtoken'
191 }
192 }
192
193
193 for module in plugins_list:
194 for module in plugins_list:
194 plugin_name = module.partition('#')[-1]
195 plugin_name = module.partition('#')[-1]
195 if plugin_name in name_map:
196 if plugin_name in name_map:
196 plugin_name = name_map[plugin_name]
197 plugin_name = name_map[plugin_name]
197 enabled_plugin = 'auth_%s_enabled' % plugin_name
198 enabled_plugin = 'auth_%s_enabled' % plugin_name
198 cache_ttl = 'auth_%s_cache_ttl' % plugin_name
199 cache_ttl = 'auth_%s_cache_ttl' % plugin_name
199
200
200 # default params that are needed for each plugin,
201 # default params that are needed for each plugin,
201 # `enabled` and `cache_ttl`
202 # `enabled` and `cache_ttl`
202 params.update({
203 params.update({
203 enabled_plugin: True,
204 enabled_plugin: True,
204 cache_ttl: 0
205 cache_ttl: 0
205 })
206 })
206 if override.get:
207 if override.get:
207 params.update(override.get(module, {}))
208 params.update(override.get(module, {}))
208
209
209 validated_params = params
210 validated_params = params
210 for k, v in validated_params.items():
211 for k, v in validated_params.items():
211 setting = SettingsModel().create_or_update_setting(k, v)
212 setting = SettingsModel().create_or_update_setting(k, v)
212 Session().add(setting)
213 Session().add(setting)
213 Session().commit()
214 Session().commit()
214
215
215 SettingsModel().invalidate_settings_cache()
216 SettingsModel().invalidate_settings_cache()
216
217
217 def cleanup():
218 def cleanup():
218 _enable_plugins(['egg:rhodecode-enterprise-ce#rhodecode'])
219 _enable_plugins(['egg:rhodecode-enterprise-ce#rhodecode'])
219
220
220 request.addfinalizer(cleanup)
221 request.addfinalizer(cleanup)
221
222
222 return _enable_plugins
223 return _enable_plugins
223
224
224
225
225 @pytest.fixture()
226 @pytest.fixture()
226 def fs_repo_only(request, rhodecode_fixtures):
227 def fs_repo_only(request, rhodecode_fixtures):
227 def fs_repo_fabric(repo_name, repo_type):
228 def fs_repo_fabric(repo_name, repo_type):
228 rhodecode_fixtures.create_repo(repo_name, repo_type=repo_type)
229 rhodecode_fixtures.create_repo(repo_name, repo_type=repo_type)
229 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=False)
230 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=False)
230
231
231 def cleanup():
232 def cleanup():
232 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=True)
233 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=True)
233 rhodecode_fixtures.destroy_repo_on_filesystem(repo_name)
234 rhodecode_fixtures.destroy_repo_on_filesystem(repo_name)
234
235
235 request.addfinalizer(cleanup)
236 request.addfinalizer(cleanup)
236
237
237 return fs_repo_fabric
238 return fs_repo_fabric
238
239
239
240
240 @pytest.fixture()
241 @pytest.fixture()
241 def enable_webhook_push_integration(request):
242 def enable_webhook_push_integration(request):
242 integration = Integration()
243 integration = Integration()
243 integration.integration_type = WebhookIntegrationType.key
244 integration.integration_type = WebhookIntegrationType.key
244 Session().add(integration)
245 Session().add(integration)
245
246
246 settings = dict(
247 settings = dict(
247 url='http://httpbin.org/post',
248 url='http://httpbin.org/post',
248 secret_token='secret',
249 secret_token='secret',
249 username=None,
250 username=None,
250 password=None,
251 password=None,
251 custom_header_key=None,
252 custom_header_key=None,
252 custom_header_val=None,
253 custom_header_val=None,
253 method_type='post',
254 method_type='post',
254 events=[events.RepoPushEvent.name],
255 events=[events.RepoPushEvent.name],
255 log_data=True
256 log_data=True
256 )
257 )
257
258
258 IntegrationModel().update_integration(
259 IntegrationModel().update_integration(
259 integration,
260 integration,
260 name='IntegrationWebhookTest',
261 name='IntegrationWebhookTest',
261 enabled=True,
262 enabled=True,
262 settings=settings,
263 settings=settings,
263 repo=None,
264 repo=None,
264 repo_group=None,
265 repo_group=None,
265 child_repos_only=False,
266 child_repos_only=False,
266 )
267 )
267 Session().commit()
268 Session().commit()
268 integration_id = integration.integration_id
269 integration_id = integration.integration_id
269
270
270 @request.addfinalizer
271 @request.addfinalizer
271 def cleanup():
272 def cleanup():
272 integration = Integration.get(integration_id)
273 integration = Integration.get(integration_id)
273 Session().delete(integration)
274 Session().delete(integration)
274 Session().commit()
275 Session().commit()
275
276
276
277
277 @pytest.fixture()
278 @pytest.fixture()
278 def branch_permission_setter(request):
279 def branch_permission_setter(request):
279 """
280 """
280
281
281 def my_test(branch_permission_setter)
282 def my_test(branch_permission_setter)
282 branch_permission_setter(repo_name, username, pattern='*', permission='branch.push')
283 branch_permission_setter(repo_name, username, pattern='*', permission='branch.push')
283
284
284 """
285 """
285
286
286 rule_id = None
287 rule_id = None
287 write_perm_id = None
288 write_perm_id = None
288 write_perm = None
289 write_perm = None
289 rule = None
290 rule = None
290
291
291 def _branch_permissions_setter(
292 def _branch_permissions_setter(
292 repo_name, username, pattern='*', permission='branch.push_force'):
293 repo_name, username, pattern='*', permission='branch.push_force'):
293 global rule_id, write_perm_id
294 global rule_id, write_perm_id
294 global rule, write_perm
295 global rule, write_perm
295
296
296 repo = Repository.get_by_repo_name(repo_name)
297 repo = Repository.get_by_repo_name(repo_name)
297 repo_id = repo.repo_id
298 repo_id = repo.repo_id
298
299
299 user = User.get_by_username(username)
300 user = User.get_by_username(username)
300 user_id = user.user_id
301 user_id = user.user_id
301
302
302 rule_perm_obj = Permission.get_by_key(permission)
303 rule_perm_obj = Permission.get_by_key(permission)
303
304
304 # add new entry, based on existing perm entry
305 # add new entry, based on existing perm entry
305 perm = UserRepoToPerm.query() \
306 perm = UserRepoToPerm.query() \
306 .filter(UserRepoToPerm.repository_id == repo_id) \
307 .filter(UserRepoToPerm.repository_id == repo_id) \
307 .filter(UserRepoToPerm.user_id == user_id) \
308 .filter(UserRepoToPerm.user_id == user_id) \
308 .first()
309 .first()
309
310
310 if not perm:
311 if not perm:
311 # such user isn't defined in Permissions for repository
312 # such user isn't defined in Permissions for repository
312 # we now on-the-fly add new permission
313 # we now on-the-fly add new permission
313
314
314 write_perm = UserRepoToPerm()
315 write_perm = UserRepoToPerm()
315 write_perm.permission = Permission.get_by_key('repository.write')
316 write_perm.permission = Permission.get_by_key('repository.write')
316 write_perm.repository_id = repo_id
317 write_perm.repository_id = repo_id
317 write_perm.user_id = user_id
318 write_perm.user_id = user_id
318 Session().add(write_perm)
319 Session().add(write_perm)
319 Session().flush()
320 Session().flush()
320
321
321 perm = write_perm
322 perm = write_perm
322
323
323 rule = UserToRepoBranchPermission()
324 rule = UserToRepoBranchPermission()
324 rule.rule_to_perm_id = perm.repo_to_perm_id
325 rule.rule_to_perm_id = perm.repo_to_perm_id
325 rule.branch_pattern = pattern
326 rule.branch_pattern = pattern
326 rule.rule_order = 10
327 rule.rule_order = 10
327 rule.permission = rule_perm_obj
328 rule.permission = rule_perm_obj
328 rule.repository_id = repo_id
329 rule.repository_id = repo_id
329 Session().add(rule)
330 Session().add(rule)
330 Session().commit()
331 Session().commit()
331
332
332 return rule
333 return rule
333
334
334 @request.addfinalizer
335 @request.addfinalizer
335 def cleanup():
336 def cleanup():
336 if rule:
337 if rule:
337 Session().delete(rule)
338 Session().delete(rule)
338 Session().commit()
339 Session().commit()
339 if write_perm:
340 if write_perm:
340 Session().delete(write_perm)
341 Session().delete(write_perm)
341 Session().commit()
342 Session().commit()
342
343
343 return _branch_permissions_setter
344 return _branch_permissions_setter
344
345
345
346
General Comments 0
You need to be logged in to leave comments. Login now