##// END OF EJS Templates
tests: fix httpbin port, within a container we use internal docker network so port is not exposed, we should call httpbin directly
super-admin -
r5153:57de8b95 default
parent child Browse files
Show More
@@ -1,132 +1,136 b''
1 1 # Copyright (C) 2010-2023 RhodeCode GmbH
2 2 #
3 3 # This program is free software: you can redistribute it and/or modify
4 4 # it under the terms of the GNU Affero General Public License, version 3
5 5 # (only), as published by the Free Software Foundation.
6 6 #
7 7 # This program is distributed in the hope that it will be useful,
8 8 # but WITHOUT ANY WARRANTY; without even the implied warranty of
9 9 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 10 # GNU General Public License for more details.
11 11 #
12 12 # You should have received a copy of the GNU Affero General Public License
13 13 # along with this program. If not, see <http://www.gnu.org/licenses/>.
14 14 #
15 15 # This program is dual-licensed. If you wish to learn more about the
16 16 # RhodeCode Enterprise Edition, including its added features, Support services,
17 17 # and proprietary license terms, please see https://rhodecode.com/licenses/
18 18
19 19 """
20 20 py.test config for test suite for making push/pull operations.
21 21
22 22 .. important::
23 23
24 24 You must have git >= 1.8.5 for tests to work fine. With 68b939b git started
25 25 to redirect things to stderr instead of stdout.
26 26 """
27 27
28 28 import pytest
29 29 import logging
30 30
31 31 from rhodecode.authentication import AuthenticationPluginRegistry
32 32 from rhodecode.model.db import Permission, User
33 33 from rhodecode.model.meta import Session
34 34 from rhodecode.model.settings import SettingsModel
35 35 from rhodecode.model.user import UserModel
36 36
37 37
38 38 log = logging.getLogger(__name__)
39 39
40 # Docker image running httpbin...
41 HTTPBIN_DOMAIN = 'http://httpbin'
42 HTTPBIN_POST = HTTPBIN_DOMAIN + '/post'
43
40 44
41 45 @pytest.fixture()
42 46 def enable_auth_plugins(request, baseapp, csrf_token):
43 47 """
44 48 Return a factory object that when called, allows to control which
45 49 authentication plugins are enabled.
46 50 """
47 51
48 52 class AuthPluginManager(object):
49 53
50 54 def cleanup(self):
51 55 self._enable_plugins(['egg:rhodecode-enterprise-ce#rhodecode'])
52 56
53 57 def enable(self, plugins_list, override=None):
54 58 return self._enable_plugins(plugins_list, override)
55 59
56 60 def _enable_plugins(self, plugins_list, override=None):
57 61 override = override or {}
58 62 params = {
59 63 'auth_plugins': ','.join(plugins_list),
60 64 }
61 65
62 66 # helper translate some names to others, to fix settings code
63 67 name_map = {
64 68 'token': 'authtoken'
65 69 }
66 70 log.debug('enable_auth_plugins: enabling following auth-plugins: %s', plugins_list)
67 71
68 72 for module in plugins_list:
69 73 plugin_name = module.partition('#')[-1]
70 74 if plugin_name in name_map:
71 75 plugin_name = name_map[plugin_name]
72 76 enabled_plugin = f'auth_{plugin_name}_enabled'
73 77 cache_ttl = f'auth_{plugin_name}_cache_ttl'
74 78
75 79 # default params that are needed for each plugin,
76 80 # `enabled` and `cache_ttl`
77 81 params.update({
78 82 enabled_plugin: True,
79 83 cache_ttl: 0
80 84 })
81 85 if override.get:
82 86 params.update(override.get(module, {}))
83 87
84 88 validated_params = params
85 89
86 90 for k, v in validated_params.items():
87 91 setting = SettingsModel().create_or_update_setting(k, v)
88 92 Session().add(setting)
89 93 Session().commit()
90 94
91 95 AuthenticationPluginRegistry.invalidate_auth_plugins_cache(hard=True)
92 96
93 97 enabled_plugins = SettingsModel().get_auth_plugins()
94 98 assert plugins_list == enabled_plugins
95 99
96 100 enabler = AuthPluginManager()
97 101 request.addfinalizer(enabler.cleanup)
98 102
99 103 return enabler
100 104
101 105
102 106 @pytest.fixture()
103 107 def test_user_factory(request, baseapp):
104 108
105 109 def user_factory(username='test_user', password='qweqwe', first_name='John', last_name='Testing', **kwargs):
106 110 usr = UserModel().create_or_update(
107 111 username=username,
108 112 password=password,
109 113 email=f'{username}@rhodecode.org',
110 114 firstname=first_name, lastname=last_name)
111 115 Session().commit()
112 116
113 117 for k, v in kwargs.items():
114 118 setattr(usr, k, v)
115 119 Session().add(usr)
116 120
117 121 assert User.get_by_username(username) == usr
118 122
119 123 @request.addfinalizer
120 124 def cleanup():
121 125 if UserModel().get_user(usr.user_id) is None:
122 126 return
123 127
124 128 perm = Permission.query().all()
125 129 for p in perm:
126 130 UserModel().revoke_perm(usr, p)
127 131
128 132 UserModel().delete(usr.user_id)
129 133 Session().commit()
130 134 return usr
131 135
132 136 return user_factory
@@ -1,58 +1,59 b''
1 1
2 2 # Copyright (C) 2010-2023 RhodeCode GmbH
3 3 #
4 4 # This program is free software: you can redistribute it and/or modify
5 5 # it under the terms of the GNU Affero General Public License, version 3
6 6 # (only), as published by the Free Software Foundation.
7 7 #
8 8 # This program is distributed in the hope that it will be useful,
9 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 11 # GNU General Public License for more details.
12 12 #
13 13 # You should have received a copy of the GNU Affero General Public License
14 14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 15 #
16 16 # This program is dual-licensed. If you wish to learn more about the
17 17 # RhodeCode Enterprise Edition, including its added features, Support services,
18 18 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 19
20 20
21 21 import pytest
22 22 from rhodecode import events
23 23 from rhodecode.lib.utils2 import AttributeDict
24 from rhodecode.tests.conftest import HTTPBIN_DOMAIN
24 25
25 26
26 27 @pytest.fixture()
27 28 def repo_push_event(backend, user_regular):
28 29 commits = [
29 30 {'message': 'ancestor commit fixes #15'},
30 31 {'message': 'quick fixes'},
31 32 {'message': 'change that fixes #41, #2'},
32 33 {'message': 'this is because 5b23c3532 broke stuff'},
33 34 {'message': 'last commit'},
34 35 ]
35 36 r = backend.create_repo(commits)
36 37
37 38 commit_ids = list(backend.commit_ids.values())
38 39 repo_name = backend.repo_name
39 40 alias = backend.alias
40 41
41 42 scm_extras = AttributeDict({
42 43 'ip': '127.0.0.1',
43 44 'username': user_regular.username,
44 45 'user_id': user_regular.user_id,
45 46 'action': '',
46 47 'repository': repo_name,
47 48 'scm': alias,
48 49 'config': '',
49 50 'repo_store': '',
50 'server_url': 'http://httpbin:9090',
51 'server_url': HTTPBIN_DOMAIN,
51 52 'make_lock': None,
52 53 'locked_by': [None],
53 54 'commit_ids': commit_ids,
54 55 })
55 56
56 57 return events.RepoPushEvent(repo_name=repo_name,
57 58 pushed_commit_ids=commit_ids,
58 59 extras=scm_extras)
@@ -1,310 +1,307 b''
1 1
2 2 # Copyright (C) 2010-2023 RhodeCode GmbH
3 3 #
4 4 # This program is free software: you can redistribute it and/or modify
5 5 # it under the terms of the GNU Affero General Public License, version 3
6 6 # (only), as published by the Free Software Foundation.
7 7 #
8 8 # This program is distributed in the hope that it will be useful,
9 9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 11 # GNU General Public License for more details.
12 12 #
13 13 # You should have received a copy of the GNU Affero General Public License
14 14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 15 #
16 16 # This program is dual-licensed. If you wish to learn more about the
17 17 # RhodeCode Enterprise Edition, including its added features, Support services,
18 18 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 19
20 20 """
21 21 py.test config for test suite for making push/pull operations.
22 22
23 23 .. important::
24 24
25 25 You must have git >= 1.8.5 for tests to work fine. With 68b939b git started
26 26 to redirect things to stderr instead of stdout.
27 27 """
28 28
29 29 import os
30 30 import tempfile
31 31 import textwrap
32 32 import pytest
33 33 import logging
34 34 import requests
35 35
36 36 from rhodecode import events
37 37 from rhodecode.lib.str_utils import safe_bytes
38 38 from rhodecode.model.db import Integration, UserRepoToPerm, Permission, \
39 39 UserToRepoBranchPermission, User
40 40 from rhodecode.model.integration import IntegrationModel
41 41 from rhodecode.model.db import Repository
42 42 from rhodecode.model.meta import Session
43 43 from rhodecode.integrations.types.webhook import WebhookIntegrationType
44 44
45 45 from rhodecode.tests import GIT_REPO, HG_REPO
46 from rhodecode.tests.conftest import HTTPBIN_DOMAIN
46 47 from rhodecode.tests.fixture import Fixture
47 48 from rhodecode.tests.server_utils import RcWebServer
48 49
49 50
50 51 REPO_GROUP = 'a_repo_group'
51 52 HG_REPO_WITH_GROUP = f'{REPO_GROUP}/{HG_REPO}'
52 53 GIT_REPO_WITH_GROUP = f'{REPO_GROUP}/{GIT_REPO}'
53 54
54 55 log = logging.getLogger(__name__)
55 56
56 # Docker image running httpbin...
57 HTTPBIN_DOMAIN = 'http://httpbin:9090'
58 HTTPBIN_POST = HTTPBIN_DOMAIN + '/post'
59
60 57
61 58 def check_httpbin_connection():
62 59 try:
63 60 response = requests.get(HTTPBIN_DOMAIN)
64 61 return response.status_code == 200
65 62 except Exception as e:
66 63 print(e)
67 64
68 65 return False
69 66
70 67
71 68 @pytest.fixture(scope="module")
72 69 def rcextensions(request, db_connection, tmpdir_factory):
73 70 """
74 71 Installs a testing rcextensions pack to ensure they work as expected.
75 72 """
76 73 init_content = textwrap.dedent("""
77 74 # Forward import the example rcextensions to make it
78 75 # active for our tests.
79 76 from rhodecode.tests.other.example_rcextensions import *
80 77 """)
81 78
82 79 # Note: rcextensions are looked up based on the path of the ini file
83 80 root_path = tmpdir_factory.getbasetemp()
84 81 rcextensions_path = root_path.join('rcextensions')
85 82 init_path = rcextensions_path.join('__init__.py')
86 83
87 84 if rcextensions_path.check():
88 85 pytest.fail(
89 86 "Path for rcextensions already exists, please clean up before "
90 87 "test run this path: %s" % (rcextensions_path, ))
91 88 else:
92 89 request.addfinalizer(rcextensions_path.remove)
93 90 init_path.write_binary(safe_bytes(init_content), ensure=True)
94 91
95 92
96 93 @pytest.fixture(scope="module")
97 94 def repos(request, db_connection):
98 95 """Create a copy of each test repo in a repo group."""
99 96 fixture = Fixture()
100 97 repo_group = fixture.create_repo_group(REPO_GROUP)
101 98 repo_group_id = repo_group.group_id
102 99 fixture.create_fork(HG_REPO, HG_REPO,
103 100 repo_name_full=HG_REPO_WITH_GROUP,
104 101 repo_group=repo_group_id)
105 102 fixture.create_fork(GIT_REPO, GIT_REPO,
106 103 repo_name_full=GIT_REPO_WITH_GROUP,
107 104 repo_group=repo_group_id)
108 105
109 106 @request.addfinalizer
110 107 def cleanup():
111 108 fixture.destroy_repo(HG_REPO_WITH_GROUP)
112 109 fixture.destroy_repo(GIT_REPO_WITH_GROUP)
113 110 fixture.destroy_repo_group(repo_group_id)
114 111
115 112
116 113 @pytest.fixture(scope="module")
117 114 def rc_web_server_config_modification():
118 115 return []
119 116
120 117
121 118 @pytest.fixture(scope="module")
122 119 def rc_web_server_config_factory(testini_factory, rc_web_server_config_modification):
123 120 """
124 121 Configuration file used for the fixture `rc_web_server`.
125 122 """
126 123
127 124 def factory(rcweb_port, vcsserver_port):
128 125 custom_params = [
129 126 {'handler_console': {'level': 'DEBUG'}},
130 127 {'server:main': {'port': rcweb_port}},
131 128 {'app:main': {'vcs.server': 'localhost:%s' % vcsserver_port}}
132 129 ]
133 130 custom_params.extend(rc_web_server_config_modification)
134 131 return testini_factory(custom_params)
135 132 return factory
136 133
137 134
138 135 @pytest.fixture(scope="module")
139 136 def rc_web_server(
140 137 request, vcsserver_factory, available_port_factory,
141 138 rc_web_server_config_factory, repos, rcextensions):
142 139 """
143 140 Run the web server as a subprocess. with its own instance of vcsserver
144 141 """
145 142 rcweb_port = available_port_factory()
146 143 log.info('Using rcweb ops test port {}'.format(rcweb_port))
147 144
148 145 vcsserver_port = available_port_factory()
149 146 log.info('Using vcsserver ops test port {}'.format(vcsserver_port))
150 147
151 148 vcs_log = os.path.join(tempfile.gettempdir(), 'rc_op_vcs.log')
152 149 vcsserver_factory(
153 150 request, vcsserver_port=vcsserver_port,
154 151 log_file=vcs_log,
155 152 overrides=(
156 153 {'server:main': {'workers': 2}},
157 154 {'server:main': {'graceful_timeout': 10}},
158 155 ))
159 156
160 157 rc_log = os.path.join(tempfile.gettempdir(), 'rc_op_web.log')
161 158 rc_web_server_config = rc_web_server_config_factory(
162 159 rcweb_port=rcweb_port,
163 160 vcsserver_port=vcsserver_port)
164 161 server = RcWebServer(rc_web_server_config, log_file=rc_log)
165 162 server.start()
166 163
167 164 @request.addfinalizer
168 165 def cleanup():
169 166 server.shutdown()
170 167
171 168 server.wait_until_ready()
172 169 return server
173 170
174 171
175 172 @pytest.fixture()
176 173 def disable_locking(baseapp):
177 174 r = Repository.get_by_repo_name(GIT_REPO)
178 175 Repository.unlock(r)
179 176 r.enable_locking = False
180 177 Session().add(r)
181 178 Session().commit()
182 179
183 180 r = Repository.get_by_repo_name(HG_REPO)
184 181 Repository.unlock(r)
185 182 r.enable_locking = False
186 183 Session().add(r)
187 184 Session().commit()
188 185
189 186
190 187 @pytest.fixture()
191 188 def fs_repo_only(request, rhodecode_fixtures):
192 189 def fs_repo_fabric(repo_name, repo_type):
193 190 rhodecode_fixtures.create_repo(repo_name, repo_type=repo_type)
194 191 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=False)
195 192
196 193 def cleanup():
197 194 rhodecode_fixtures.destroy_repo(repo_name, fs_remove=True)
198 195 rhodecode_fixtures.destroy_repo_on_filesystem(repo_name)
199 196
200 197 request.addfinalizer(cleanup)
201 198
202 199 return fs_repo_fabric
203 200
204 201
205 202 @pytest.fixture()
206 203 def enable_webhook_push_integration(request):
207 204 integration = Integration()
208 205 integration.integration_type = WebhookIntegrationType.key
209 206 Session().add(integration)
210 207
211 208 settings = dict(
212 209 url=HTTPBIN_POST,
213 210 secret_token='secret',
214 211 username=None,
215 212 password=None,
216 213 custom_header_key=None,
217 214 custom_header_val=None,
218 215 method_type='post',
219 216 events=[events.RepoPushEvent.name],
220 217 log_data=True
221 218 )
222 219
223 220 IntegrationModel().update_integration(
224 221 integration,
225 222 name='IntegrationWebhookTest',
226 223 enabled=True,
227 224 settings=settings,
228 225 repo=None,
229 226 repo_group=None,
230 227 child_repos_only=False,
231 228 )
232 229 Session().commit()
233 230 integration_id = integration.integration_id
234 231
235 232 @request.addfinalizer
236 233 def cleanup():
237 234 integration = Integration.get(integration_id)
238 235 Session().delete(integration)
239 236 Session().commit()
240 237
241 238
242 239 @pytest.fixture()
243 240 def branch_permission_setter(request):
244 241 """
245 242
246 243 def my_test(branch_permission_setter)
247 244 branch_permission_setter(repo_name, username, pattern='*', permission='branch.push')
248 245
249 246 """
250 247
251 248 rule_id = None
252 249 write_perm_id = None
253 250 write_perm = None
254 251 rule = None
255 252
256 253 def _branch_permissions_setter(
257 254 repo_name, username, pattern='*', permission='branch.push_force'):
258 255 global rule_id, write_perm_id
259 256 global rule, write_perm
260 257
261 258 repo = Repository.get_by_repo_name(repo_name)
262 259 repo_id = repo.repo_id
263 260
264 261 user = User.get_by_username(username)
265 262 user_id = user.user_id
266 263
267 264 rule_perm_obj = Permission.get_by_key(permission)
268 265
269 266 # add new entry, based on existing perm entry
270 267 perm = UserRepoToPerm.query() \
271 268 .filter(UserRepoToPerm.repository_id == repo_id) \
272 269 .filter(UserRepoToPerm.user_id == user_id) \
273 270 .first()
274 271
275 272 if not perm:
276 273 # such user isn't defined in Permissions for repository
277 274 # we now on-the-fly add new permission
278 275
279 276 write_perm = UserRepoToPerm()
280 277 write_perm.permission = Permission.get_by_key('repository.write')
281 278 write_perm.repository_id = repo_id
282 279 write_perm.user_id = user_id
283 280 Session().add(write_perm)
284 281 Session().flush()
285 282
286 283 perm = write_perm
287 284
288 285 rule = UserToRepoBranchPermission()
289 286 rule.rule_to_perm_id = perm.repo_to_perm_id
290 287 rule.branch_pattern = pattern
291 288 rule.rule_order = 10
292 289 rule.permission = rule_perm_obj
293 290 rule.repository_id = repo_id
294 291 Session().add(rule)
295 292 Session().commit()
296 293
297 294 return rule
298 295
299 296 @request.addfinalizer
300 297 def cleanup():
301 298 if rule:
302 299 Session().delete(rule)
303 300 Session().commit()
304 301 if write_perm:
305 302 Session().delete(write_perm)
306 303 Session().commit()
307 304
308 305 return _branch_permissions_setter
309 306
310 307
General Comments 0
You need to be logged in to leave comments. Login now