##// END OF EJS Templates
more usage of fixture tools...
marcink -
r3647:8a86836f beta
parent child Browse files
Show More
@@ -1,210 +1,175 b''
1 """Pylons application test package
1 """Pylons application test package
2
2
3 This package assumes the Pylons environment is already loaded, such as
3 This package assumes the Pylons environment is already loaded, such as
4 when this script is imported from the `nosetests --with-pylons=test.ini`
4 when this script is imported from the `nosetests --with-pylons=test.ini`
5 command.
5 command.
6
6
7 This module initializes the application via ``websetup`` (`paster
7 This module initializes the application via ``websetup`` (`paster
8 setup-app`) and provides the base testing objects.
8 setup-app`) and provides the base testing objects.
9
9
10 nosetests -x - fail on first error
10 nosetests -x - fail on first error
11 nosetests rhodecode.tests.functional.test_admin_settings:TestSettingsController.test_my_account
11 nosetests rhodecode.tests.functional.test_admin_settings:TestSettingsController.test_my_account
12 nosetests --pdb --pdb-failures
12 nosetests --pdb --pdb-failures
13 nosetests --with-coverage --cover-package=rhodecode.model.validators rhodecode.tests.test_validators
13 nosetests --with-coverage --cover-package=rhodecode.model.validators rhodecode.tests.test_validators
14
14
15 optional FLAGS:
15 optional FLAGS:
16 RC_WHOOSH_TEST_DISABLE=1 - skip whoosh index building and tests
16 RC_WHOOSH_TEST_DISABLE=1 - skip whoosh index building and tests
17 RC_NO_TMP_PATH=1 - disable new temp path for tests, used mostly for test_vcs_operations
17 RC_NO_TMP_PATH=1 - disable new temp path for tests, used mostly for test_vcs_operations
18
18
19 """
19 """
20 import os
20 import os
21 import time
21 import time
22 import logging
22 import logging
23 import datetime
23 import datetime
24 import hashlib
24 import hashlib
25 import tempfile
25 import tempfile
26 from os.path import join as jn
26 from os.path import join as jn
27
27
28 from unittest import TestCase
28 from unittest import TestCase
29 from tempfile import _RandomNameSequence
29 from tempfile import _RandomNameSequence
30
30
31 from paste.deploy import loadapp
31 from paste.deploy import loadapp
32 from paste.script.appinstall import SetupCommand
32 from paste.script.appinstall import SetupCommand
33 from pylons import config, url
33 from pylons import config, url
34 from routes.util import URLGenerator
34 from routes.util import URLGenerator
35 from webtest import TestApp
35 from webtest import TestApp
36 from nose.plugins.skip import SkipTest
36 from nose.plugins.skip import SkipTest
37
37
38 from rhodecode import is_windows
38 from rhodecode import is_windows
39 from rhodecode.model.meta import Session
39 from rhodecode.model.meta import Session
40 from rhodecode.model.db import User
40 from rhodecode.model.db import User
41 from rhodecode.tests.nose_parametrized import parameterized
41 from rhodecode.tests.nose_parametrized import parameterized
42
42
43 import pylons.test
43 import pylons.test
44 from rhodecode.lib.utils2 import safe_unicode, safe_str
44 from rhodecode.lib.utils2 import safe_unicode, safe_str
45
45
46
46
47 os.environ['TZ'] = 'UTC'
47 os.environ['TZ'] = 'UTC'
48 if not is_windows:
48 if not is_windows:
49 time.tzset()
49 time.tzset()
50
50
51 log = logging.getLogger(__name__)
51 log = logging.getLogger(__name__)
52
52
53 __all__ = [
53 __all__ = [
54 'parameterized', 'environ', 'url', 'get_new_dir', 'TestController',
54 'parameterized', 'environ', 'url', 'get_new_dir', 'TestController',
55 'SkipTest',
55 'SkipTest',
56 'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'NEW_HG_REPO', 'NEW_GIT_REPO',
56 'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'NEW_HG_REPO', 'NEW_GIT_REPO',
57 'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
57 'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
58 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
58 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
59 'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
59 'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
60 'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
60 'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
61 'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
61 'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
62 'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'HG_REMOTE_REPO',
62 'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'HG_REMOTE_REPO',
63 'GIT_REMOTE_REPO', 'SCM_TESTS', '_get_repo_create_params',
63 'GIT_REMOTE_REPO', 'SCM_TESTS',
64 '_get_group_create_params'
65 ]
64 ]
66
65
67 # Invoke websetup with the current config file
66 # Invoke websetup with the current config file
68 # SetupCommand('setup-app').run([config_file])
67 # SetupCommand('setup-app').run([config_file])
69
68
70 environ = {}
69 environ = {}
71
70
72 #SOME GLOBALS FOR TESTS
71 #SOME GLOBALS FOR TESTS
73
72
74 TESTS_TMP_PATH = jn('/', 'tmp', 'rc_test_%s' % _RandomNameSequence().next())
73 TESTS_TMP_PATH = jn('/', 'tmp', 'rc_test_%s' % _RandomNameSequence().next())
75 TEST_USER_ADMIN_LOGIN = 'test_admin'
74 TEST_USER_ADMIN_LOGIN = 'test_admin'
76 TEST_USER_ADMIN_PASS = 'test12'
75 TEST_USER_ADMIN_PASS = 'test12'
77 TEST_USER_ADMIN_EMAIL = 'test_admin@mail.com'
76 TEST_USER_ADMIN_EMAIL = 'test_admin@mail.com'
78
77
79 TEST_USER_REGULAR_LOGIN = 'test_regular'
78 TEST_USER_REGULAR_LOGIN = 'test_regular'
80 TEST_USER_REGULAR_PASS = 'test12'
79 TEST_USER_REGULAR_PASS = 'test12'
81 TEST_USER_REGULAR_EMAIL = 'test_regular@mail.com'
80 TEST_USER_REGULAR_EMAIL = 'test_regular@mail.com'
82
81
83 TEST_USER_REGULAR2_LOGIN = 'test_regular2'
82 TEST_USER_REGULAR2_LOGIN = 'test_regular2'
84 TEST_USER_REGULAR2_PASS = 'test12'
83 TEST_USER_REGULAR2_PASS = 'test12'
85 TEST_USER_REGULAR2_EMAIL = 'test_regular2@mail.com'
84 TEST_USER_REGULAR2_EMAIL = 'test_regular2@mail.com'
86
85
87 HG_REPO = 'vcs_test_hg'
86 HG_REPO = 'vcs_test_hg'
88 GIT_REPO = 'vcs_test_git'
87 GIT_REPO = 'vcs_test_git'
89
88
90 NEW_HG_REPO = 'vcs_test_hg_new'
89 NEW_HG_REPO = 'vcs_test_hg_new'
91 NEW_GIT_REPO = 'vcs_test_git_new'
90 NEW_GIT_REPO = 'vcs_test_git_new'
92
91
93 HG_FORK = 'vcs_test_hg_fork'
92 HG_FORK = 'vcs_test_hg_fork'
94 GIT_FORK = 'vcs_test_git_fork'
93 GIT_FORK = 'vcs_test_git_fork'
95
94
96 ## VCS
95 ## VCS
97 SCM_TESTS = ['hg', 'git']
96 SCM_TESTS = ['hg', 'git']
98 uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
97 uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
99
98
100 GIT_REMOTE_REPO = 'git://github.com/codeinn/vcs.git'
99 GIT_REMOTE_REPO = 'git://github.com/codeinn/vcs.git'
101
100
102 TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
101 TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
103 TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
102 TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
104 TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
103 TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
105
104
106
105
107 HG_REMOTE_REPO = 'http://bitbucket.org/marcinkuzminski/vcs'
106 HG_REMOTE_REPO = 'http://bitbucket.org/marcinkuzminski/vcs'
108
107
109 TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
108 TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
110 TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
109 TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
111 TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
110 TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
112
111
113 TEST_DIR = tempfile.gettempdir()
112 TEST_DIR = tempfile.gettempdir()
114 TEST_REPO_PREFIX = 'vcs-test'
113 TEST_REPO_PREFIX = 'vcs-test'
115
114
116 # cached repos if any !
115 # cached repos if any !
117 # comment out to get some other repos from bb or github
116 # comment out to get some other repos from bb or github
118 GIT_REMOTE_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
117 GIT_REMOTE_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
119 HG_REMOTE_REPO = jn(TESTS_TMP_PATH, HG_REPO)
118 HG_REMOTE_REPO = jn(TESTS_TMP_PATH, HG_REPO)
120
119
121
120
122 def get_new_dir(title):
121 def get_new_dir(title):
123 """
122 """
124 Returns always new directory path.
123 Returns always new directory path.
125 """
124 """
126 from rhodecode.tests.vcs.utils import get_normalized_path
125 from rhodecode.tests.vcs.utils import get_normalized_path
127 name = TEST_REPO_PREFIX
126 name = TEST_REPO_PREFIX
128 if title:
127 if title:
129 name = '-'.join((name, title))
128 name = '-'.join((name, title))
130 hex = hashlib.sha1(str(time.time())).hexdigest()
129 hex = hashlib.sha1(str(time.time())).hexdigest()
131 name = '-'.join((name, hex))
130 name = '-'.join((name, hex))
132 path = os.path.join(TEST_DIR, name)
131 path = os.path.join(TEST_DIR, name)
133 return get_normalized_path(path)
132 return get_normalized_path(path)
134
133
135
134
136 class TestController(TestCase):
135 class TestController(TestCase):
137
136
138 def __init__(self, *args, **kwargs):
137 def __init__(self, *args, **kwargs):
139 wsgiapp = pylons.test.pylonsapp
138 wsgiapp = pylons.test.pylonsapp
140 config = wsgiapp.config
139 config = wsgiapp.config
141
140
142 self.app = TestApp(wsgiapp)
141 self.app = TestApp(wsgiapp)
143 url._push_object(URLGenerator(config['routes.map'], environ))
142 url._push_object(URLGenerator(config['routes.map'], environ))
144 self.Session = Session
143 self.Session = Session
145 self.index_location = config['app_conf']['index_dir']
144 self.index_location = config['app_conf']['index_dir']
146 TestCase.__init__(self, *args, **kwargs)
145 TestCase.__init__(self, *args, **kwargs)
147
146
148 def log_user(self, username=TEST_USER_ADMIN_LOGIN,
147 def log_user(self, username=TEST_USER_ADMIN_LOGIN,
149 password=TEST_USER_ADMIN_PASS):
148 password=TEST_USER_ADMIN_PASS):
150 self._logged_username = username
149 self._logged_username = username
151 response = self.app.post(url(controller='login', action='index'),
150 response = self.app.post(url(controller='login', action='index'),
152 {'username': username,
151 {'username': username,
153 'password': password})
152 'password': password})
154
153
155 if 'invalid user name' in response.body:
154 if 'invalid user name' in response.body:
156 self.fail('could not login using %s %s' % (username, password))
155 self.fail('could not login using %s %s' % (username, password))
157
156
158 self.assertEqual(response.status, '302 Found')
157 self.assertEqual(response.status, '302 Found')
159 ses = response.session['rhodecode_user']
158 ses = response.session['rhodecode_user']
160 self.assertEqual(ses.get('username'), username)
159 self.assertEqual(ses.get('username'), username)
161 response = response.follow()
160 response = response.follow()
162 self.assertEqual(ses.get('is_authenticated'), True)
161 self.assertEqual(ses.get('is_authenticated'), True)
163
162
164 return response.session['rhodecode_user']
163 return response.session['rhodecode_user']
165
164
166 def _get_logged_user(self):
165 def _get_logged_user(self):
167 return User.get_by_username(self._logged_username)
166 return User.get_by_username(self._logged_username)
168
167
169 def checkSessionFlash(self, response, msg):
168 def checkSessionFlash(self, response, msg):
170 self.assertTrue('flash' in response.session,
169 self.assertTrue('flash' in response.session,
171 msg='Response session:%r have no flash'
170 msg='Response session:%r have no flash'
172 % response.session)
171 % response.session)
173 if not msg in response.session['flash'][0][1]:
172 if not msg in response.session['flash'][0][1]:
174 msg = u'msg `%s` not found in session flash: got `%s` instead' % (
173 msg = u'msg `%s` not found in session flash: got `%s` instead' % (
175 msg, response.session['flash'][0][1])
174 msg, response.session['flash'][0][1])
176 self.fail(safe_str(msg))
175 self.fail(safe_str(msg))
177
178
179 ## HELPERS ##
180
181 def _get_repo_create_params(**custom):
182 defs = {
183 'repo_name': None,
184 'repo_type': 'hg',
185 'clone_uri': '',
186 'repo_group': '',
187 'repo_description': 'DESC',
188 'repo_private': False,
189 'repo_landing_rev': 'tip'
190 }
191 defs.update(custom)
192 if 'repo_name_full' not in custom:
193 defs.update({'repo_name_full': defs['repo_name']})
194
195 return defs
196
197
198 def _get_group_create_params(**custom):
199 defs = dict(
200 group_name=None,
201 group_description='DESC',
202 group_parent_id=None,
203 perms_updates=[],
204 perms_new=[],
205 enable_locking=False,
206 recursive=False
207 )
208 defs.update(custom)
209
210 return defs
@@ -1,1331 +1,1311 b''
1 from __future__ import with_statement
1 from __future__ import with_statement
2 import random
2 import random
3 import mock
3 import mock
4
4
5 from rhodecode.tests import *
5 from rhodecode.tests import *
6 from rhodecode.tests.fixture import Fixture
6 from rhodecode.lib.compat import json
7 from rhodecode.lib.compat import json
7 from rhodecode.lib.auth import AuthUser
8 from rhodecode.lib.auth import AuthUser
8 from rhodecode.model.user import UserModel
9 from rhodecode.model.user import UserModel
9 from rhodecode.model.users_group import UserGroupModel
10 from rhodecode.model.users_group import UserGroupModel
10 from rhodecode.model.repo import RepoModel
11 from rhodecode.model.repo import RepoModel
11 from rhodecode.model.meta import Session
12 from rhodecode.model.meta import Session
12 from rhodecode.model.scm import ScmModel
13 from rhodecode.model.scm import ScmModel
13 from rhodecode.model.db import Repository
14 from rhodecode.model.db import Repository
14
15
16
15 API_URL = '/_admin/api'
17 API_URL = '/_admin/api'
18 TEST_USER_GROUP = 'test_users_group'
19
20 fixture = Fixture()
16
21
17
22
18 def _build_data(apikey, method, **kw):
23 def _build_data(apikey, method, **kw):
19 """
24 """
20 Builds API data with given random ID
25 Builds API data with given random ID
21
26
22 :param random_id:
27 :param random_id:
23 :type random_id:
28 :type random_id:
24 """
29 """
25 random_id = random.randrange(1, 9999)
30 random_id = random.randrange(1, 9999)
26 return random_id, json.dumps({
31 return random_id, json.dumps({
27 "id": random_id,
32 "id": random_id,
28 "api_key": apikey,
33 "api_key": apikey,
29 "method": method,
34 "method": method,
30 "args": kw
35 "args": kw
31 })
36 })
32
37
33 jsonify = lambda obj: json.loads(json.dumps(obj))
38 jsonify = lambda obj: json.loads(json.dumps(obj))
34
39
35
40
36 def crash(*args, **kwargs):
41 def crash(*args, **kwargs):
37 raise Exception('Total Crash !')
42 raise Exception('Total Crash !')
38
43
39
44
40 def api_call(test_obj, params):
45 def api_call(test_obj, params):
41 response = test_obj.app.post(API_URL, content_type='application/json',
46 response = test_obj.app.post(API_URL, content_type='application/json',
42 params=params)
47 params=params)
43 return response
48 return response
44
49
45
50
46 TEST_USER_GROUP = 'test_users_group'
51 ## helpers
47
48
49 def make_users_group(name=TEST_USER_GROUP):
52 def make_users_group(name=TEST_USER_GROUP):
50 gr = UserGroupModel().create(name=name)
53 gr = UserGroupModel().create(name=name)
51 UserGroupModel().add_user_to_group(users_group=gr,
54 UserGroupModel().add_user_to_group(users_group=gr,
52 user=TEST_USER_ADMIN_LOGIN)
55 user=TEST_USER_ADMIN_LOGIN)
53 Session().commit()
56 Session().commit()
54 return gr
57 return gr
55
58
56
59
57 def destroy_users_group(name=TEST_USER_GROUP):
60 def destroy_users_group(name=TEST_USER_GROUP):
58 UserGroupModel().delete(users_group=name, force=True)
61 UserGroupModel().delete(users_group=name, force=True)
59 Session().commit()
62 Session().commit()
60
63
61
64
62 def create_repo(repo_name, repo_type, owner=None):
63 # create new repo
64 form_data = _get_repo_create_params(
65 repo_name_full=repo_name,
66 repo_description='description %s' % repo_name,
67 )
68 cur_user = UserModel().get_by_username(owner or TEST_USER_ADMIN_LOGIN)
69 r = RepoModel().create(form_data, cur_user)
70 Session().commit()
71 return r
72
73
74 def create_fork(fork_name, fork_type, fork_of):
75 fork = RepoModel(Session())._get_repo(fork_of)
76 r = create_repo(fork_name, fork_type)
77 r.fork = fork
78 Session().add(r)
79 Session().commit()
80 return r
81
82
83 def destroy_repo(repo_name):
84 RepoModel().delete(repo_name)
85 Session().commit()
86
87
88 class BaseTestApi(object):
65 class BaseTestApi(object):
89 REPO = None
66 REPO = None
90 REPO_TYPE = None
67 REPO_TYPE = None
91
68
92 @classmethod
69 @classmethod
93 def setUpClass(self):
70 def setUpClass(self):
94 self.usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
71 self.usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
95 self.apikey = self.usr.api_key
72 self.apikey = self.usr.api_key
96 self.test_user = UserModel().create_or_update(
73 self.test_user = UserModel().create_or_update(
97 username='test-api',
74 username='test-api',
98 password='test',
75 password='test',
99 email='test@api.rhodecode.org',
76 email='test@api.rhodecode.org',
100 firstname='first',
77 firstname='first',
101 lastname='last'
78 lastname='last'
102 )
79 )
103 Session().commit()
80 Session().commit()
104 self.TEST_USER_LOGIN = self.test_user.username
81 self.TEST_USER_LOGIN = self.test_user.username
105 self.apikey_regular = self.test_user.api_key
82 self.apikey_regular = self.test_user.api_key
106
83
107 @classmethod
84 @classmethod
108 def teardownClass(self):
85 def teardownClass(self):
109 pass
86 pass
110
87
111 def setUp(self):
88 def setUp(self):
112 self.maxDiff = None
89 self.maxDiff = None
113 make_users_group()
90 make_users_group()
114
91
115 def tearDown(self):
92 def tearDown(self):
116 destroy_users_group()
93 destroy_users_group()
117
94
118 def _compare_ok(self, id_, expected, given):
95 def _compare_ok(self, id_, expected, given):
119 expected = jsonify({
96 expected = jsonify({
120 'id': id_,
97 'id': id_,
121 'error': None,
98 'error': None,
122 'result': expected
99 'result': expected
123 })
100 })
124 given = json.loads(given)
101 given = json.loads(given)
125 self.assertEqual(expected, given)
102 self.assertEqual(expected, given)
126
103
127 def _compare_error(self, id_, expected, given):
104 def _compare_error(self, id_, expected, given):
128 expected = jsonify({
105 expected = jsonify({
129 'id': id_,
106 'id': id_,
130 'error': expected,
107 'error': expected,
131 'result': None
108 'result': None
132 })
109 })
133 given = json.loads(given)
110 given = json.loads(given)
134 self.assertEqual(expected, given)
111 self.assertEqual(expected, given)
135
112
136 # def test_Optional(self):
113 # def test_Optional(self):
137 # from rhodecode.controllers.api.api import Optional
114 # from rhodecode.controllers.api.api import Optional
138 # option1 = Optional(None)
115 # option1 = Optional(None)
139 # self.assertEqual('<Optional:%s>' % None, repr(option1))
116 # self.assertEqual('<Optional:%s>' % None, repr(option1))
140 #
117 #
141 # self.assertEqual(1, Optional.extract(Optional(1)))
118 # self.assertEqual(1, Optional.extract(Optional(1)))
142 # self.assertEqual('trololo', Optional.extract('trololo'))
119 # self.assertEqual('trololo', Optional.extract('trololo'))
143
120
144 def test_api_wrong_key(self):
121 def test_api_wrong_key(self):
145 id_, params = _build_data('trololo', 'get_user')
122 id_, params = _build_data('trololo', 'get_user')
146 response = api_call(self, params)
123 response = api_call(self, params)
147
124
148 expected = 'Invalid API KEY'
125 expected = 'Invalid API KEY'
149 self._compare_error(id_, expected, given=response.body)
126 self._compare_error(id_, expected, given=response.body)
150
127
151 def test_api_missing_non_optional_param(self):
128 def test_api_missing_non_optional_param(self):
152 id_, params = _build_data(self.apikey, 'get_repo')
129 id_, params = _build_data(self.apikey, 'get_repo')
153 response = api_call(self, params)
130 response = api_call(self, params)
154
131
155 expected = 'Missing non optional `repoid` arg in JSON DATA'
132 expected = 'Missing non optional `repoid` arg in JSON DATA'
156 self._compare_error(id_, expected, given=response.body)
133 self._compare_error(id_, expected, given=response.body)
157
134
158 def test_api_missing_non_optional_param_args_null(self):
135 def test_api_missing_non_optional_param_args_null(self):
159 id_, params = _build_data(self.apikey, 'get_repo')
136 id_, params = _build_data(self.apikey, 'get_repo')
160 params = params.replace('"args": {}', '"args": null')
137 params = params.replace('"args": {}', '"args": null')
161 response = api_call(self, params)
138 response = api_call(self, params)
162
139
163 expected = 'Missing non optional `repoid` arg in JSON DATA'
140 expected = 'Missing non optional `repoid` arg in JSON DATA'
164 self._compare_error(id_, expected, given=response.body)
141 self._compare_error(id_, expected, given=response.body)
165
142
166 def test_api_missing_non_optional_param_args_bad(self):
143 def test_api_missing_non_optional_param_args_bad(self):
167 id_, params = _build_data(self.apikey, 'get_repo')
144 id_, params = _build_data(self.apikey, 'get_repo')
168 params = params.replace('"args": {}', '"args": 1')
145 params = params.replace('"args": {}', '"args": 1')
169 response = api_call(self, params)
146 response = api_call(self, params)
170
147
171 expected = 'Missing non optional `repoid` arg in JSON DATA'
148 expected = 'Missing non optional `repoid` arg in JSON DATA'
172 self._compare_error(id_, expected, given=response.body)
149 self._compare_error(id_, expected, given=response.body)
173
150
174 def test_api_args_is_null(self):
151 def test_api_args_is_null(self):
175 id_, params = _build_data(self.apikey, 'get_users',)
152 id_, params = _build_data(self.apikey, 'get_users',)
176 params = params.replace('"args": {}', '"args": null')
153 params = params.replace('"args": {}', '"args": null')
177 response = api_call(self, params)
154 response = api_call(self, params)
178 self.assertEqual(response.status, '200 OK')
155 self.assertEqual(response.status, '200 OK')
179
156
180 def test_api_args_is_bad(self):
157 def test_api_args_is_bad(self):
181 id_, params = _build_data(self.apikey, 'get_users',)
158 id_, params = _build_data(self.apikey, 'get_users',)
182 params = params.replace('"args": {}', '"args": 1')
159 params = params.replace('"args": {}', '"args": 1')
183 response = api_call(self, params)
160 response = api_call(self, params)
184 self.assertEqual(response.status, '200 OK')
161 self.assertEqual(response.status, '200 OK')
185
162
186 def test_api_get_users(self):
163 def test_api_get_users(self):
187 id_, params = _build_data(self.apikey, 'get_users',)
164 id_, params = _build_data(self.apikey, 'get_users',)
188 response = api_call(self, params)
165 response = api_call(self, params)
189 ret_all = []
166 ret_all = []
190 for usr in UserModel().get_all():
167 for usr in UserModel().get_all():
191 ret = usr.get_api_data()
168 ret = usr.get_api_data()
192 ret_all.append(jsonify(ret))
169 ret_all.append(jsonify(ret))
193 expected = ret_all
170 expected = ret_all
194 self._compare_ok(id_, expected, given=response.body)
171 self._compare_ok(id_, expected, given=response.body)
195
172
196 def test_api_get_user(self):
173 def test_api_get_user(self):
197 id_, params = _build_data(self.apikey, 'get_user',
174 id_, params = _build_data(self.apikey, 'get_user',
198 userid=TEST_USER_ADMIN_LOGIN)
175 userid=TEST_USER_ADMIN_LOGIN)
199 response = api_call(self, params)
176 response = api_call(self, params)
200
177
201 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
178 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
202 ret = usr.get_api_data()
179 ret = usr.get_api_data()
203 ret['permissions'] = AuthUser(usr.user_id).permissions
180 ret['permissions'] = AuthUser(usr.user_id).permissions
204
181
205 expected = ret
182 expected = ret
206 self._compare_ok(id_, expected, given=response.body)
183 self._compare_ok(id_, expected, given=response.body)
207
184
208 def test_api_get_user_that_does_not_exist(self):
185 def test_api_get_user_that_does_not_exist(self):
209 id_, params = _build_data(self.apikey, 'get_user',
186 id_, params = _build_data(self.apikey, 'get_user',
210 userid='trololo')
187 userid='trololo')
211 response = api_call(self, params)
188 response = api_call(self, params)
212
189
213 expected = "user `%s` does not exist" % 'trololo'
190 expected = "user `%s` does not exist" % 'trololo'
214 self._compare_error(id_, expected, given=response.body)
191 self._compare_error(id_, expected, given=response.body)
215
192
216 def test_api_get_user_without_giving_userid(self):
193 def test_api_get_user_without_giving_userid(self):
217 id_, params = _build_data(self.apikey, 'get_user')
194 id_, params = _build_data(self.apikey, 'get_user')
218 response = api_call(self, params)
195 response = api_call(self, params)
219
196
220 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
197 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
221 ret = usr.get_api_data()
198 ret = usr.get_api_data()
222 ret['permissions'] = AuthUser(usr.user_id).permissions
199 ret['permissions'] = AuthUser(usr.user_id).permissions
223
200
224 expected = ret
201 expected = ret
225 self._compare_ok(id_, expected, given=response.body)
202 self._compare_ok(id_, expected, given=response.body)
226
203
227 def test_api_get_user_without_giving_userid_non_admin(self):
204 def test_api_get_user_without_giving_userid_non_admin(self):
228 id_, params = _build_data(self.apikey_regular, 'get_user')
205 id_, params = _build_data(self.apikey_regular, 'get_user')
229 response = api_call(self, params)
206 response = api_call(self, params)
230
207
231 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
208 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
232 ret = usr.get_api_data()
209 ret = usr.get_api_data()
233 ret['permissions'] = AuthUser(usr.user_id).permissions
210 ret['permissions'] = AuthUser(usr.user_id).permissions
234
211
235 expected = ret
212 expected = ret
236 self._compare_ok(id_, expected, given=response.body)
213 self._compare_ok(id_, expected, given=response.body)
237
214
238 def test_api_get_user_with_giving_userid_non_admin(self):
215 def test_api_get_user_with_giving_userid_non_admin(self):
239 id_, params = _build_data(self.apikey_regular, 'get_user',
216 id_, params = _build_data(self.apikey_regular, 'get_user',
240 userid=self.TEST_USER_LOGIN)
217 userid=self.TEST_USER_LOGIN)
241 response = api_call(self, params)
218 response = api_call(self, params)
242
219
243 expected = 'userid is not the same as your user'
220 expected = 'userid is not the same as your user'
244 self._compare_error(id_, expected, given=response.body)
221 self._compare_error(id_, expected, given=response.body)
245
222
246 def test_api_pull(self):
223 def test_api_pull(self):
247 #TODO: issues with rhodecode_extras here.. not sure why !
224 #TODO: issues with rhodecode_extras here.. not sure why !
248 pass
225 pass
249
226
250 # repo_name = 'test_pull'
227 # repo_name = 'test_pull'
251 # r = create_repo(repo_name, self.REPO_TYPE)
228 # r = fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
252 # r.clone_uri = TEST_self.REPO
229 # r.clone_uri = TEST_self.REPO
253 # Session.add(r)
230 # Session.add(r)
254 # Session.commit()
231 # Session.commit()
255 #
232 #
256 # id_, params = _build_data(self.apikey, 'pull',
233 # id_, params = _build_data(self.apikey, 'pull',
257 # repoid=repo_name,)
234 # repoid=repo_name,)
258 # response = self.app.post(API_URL, content_type='application/json',
235 # response = self.app.post(API_URL, content_type='application/json',
259 # params=params)
236 # params=params)
260 #
237 #
261 # expected = 'Pulled from `%s`' % repo_name
238 # expected = 'Pulled from `%s`' % repo_name
262 # self._compare_ok(id_, expected, given=response.body)
239 # self._compare_ok(id_, expected, given=response.body)
263 #
240 #
264 # destroy_repo(repo_name)
241 # fixture.destroy_repo(repo_name)
265
242
266 def test_api_pull_error(self):
243 def test_api_pull_error(self):
267 id_, params = _build_data(self.apikey, 'pull',
244 id_, params = _build_data(self.apikey, 'pull',
268 repoid=self.REPO,)
245 repoid=self.REPO,)
269 response = api_call(self, params)
246 response = api_call(self, params)
270
247
271 expected = 'Unable to pull changes from `%s`' % self.REPO
248 expected = 'Unable to pull changes from `%s`' % self.REPO
272 self._compare_error(id_, expected, given=response.body)
249 self._compare_error(id_, expected, given=response.body)
273
250
274 def test_api_rescan_repos(self):
251 def test_api_rescan_repos(self):
275 id_, params = _build_data(self.apikey, 'rescan_repos')
252 id_, params = _build_data(self.apikey, 'rescan_repos')
276 response = api_call(self, params)
253 response = api_call(self, params)
277
254
278 expected = {'added': [], 'removed': []}
255 expected = {'added': [], 'removed': []}
279 self._compare_ok(id_, expected, given=response.body)
256 self._compare_ok(id_, expected, given=response.body)
280
257
281 @mock.patch.object(ScmModel, 'repo_scan', crash)
258 @mock.patch.object(ScmModel, 'repo_scan', crash)
282 def test_api_rescann_error(self):
259 def test_api_rescann_error(self):
283 id_, params = _build_data(self.apikey, 'rescan_repos',)
260 id_, params = _build_data(self.apikey, 'rescan_repos',)
284 response = api_call(self, params)
261 response = api_call(self, params)
285
262
286 expected = 'Error occurred during rescan repositories action'
263 expected = 'Error occurred during rescan repositories action'
287 self._compare_error(id_, expected, given=response.body)
264 self._compare_error(id_, expected, given=response.body)
288
265
289 def test_api_invalidate_cache(self):
266 def test_api_invalidate_cache(self):
290 id_, params = _build_data(self.apikey, 'invalidate_cache',
267 id_, params = _build_data(self.apikey, 'invalidate_cache',
291 repoid=self.REPO)
268 repoid=self.REPO)
292 response = api_call(self, params)
269 response = api_call(self, params)
293
270
294 expected = ("Cache for repository `%s` was invalidated: "
271 expected = ("Cache for repository `%s` was invalidated: "
295 "invalidated cache keys: %s" % (self.REPO,
272 "invalidated cache keys: %s" % (self.REPO,
296 [unicode(self.REPO)]))
273 [unicode(self.REPO)]))
297 self._compare_ok(id_, expected, given=response.body)
274 self._compare_ok(id_, expected, given=response.body)
298
275
299 @mock.patch.object(ScmModel, 'mark_for_invalidation', crash)
276 @mock.patch.object(ScmModel, 'mark_for_invalidation', crash)
300 def test_api_invalidate_cache_error(self):
277 def test_api_invalidate_cache_error(self):
301 id_, params = _build_data(self.apikey, 'invalidate_cache',
278 id_, params = _build_data(self.apikey, 'invalidate_cache',
302 repoid=self.REPO)
279 repoid=self.REPO)
303 response = api_call(self, params)
280 response = api_call(self, params)
304
281
305 expected = 'Error occurred during cache invalidation action'
282 expected = 'Error occurred during cache invalidation action'
306 self._compare_error(id_, expected, given=response.body)
283 self._compare_error(id_, expected, given=response.body)
307
284
308 def test_api_lock_repo_lock_aquire(self):
285 def test_api_lock_repo_lock_aquire(self):
309 id_, params = _build_data(self.apikey, 'lock',
286 id_, params = _build_data(self.apikey, 'lock',
310 userid=TEST_USER_ADMIN_LOGIN,
287 userid=TEST_USER_ADMIN_LOGIN,
311 repoid=self.REPO,
288 repoid=self.REPO,
312 locked=True)
289 locked=True)
313 response = api_call(self, params)
290 response = api_call(self, params)
314 expected = ('User `%s` set lock state for repo `%s` to `%s`'
291 expected = ('User `%s` set lock state for repo `%s` to `%s`'
315 % (TEST_USER_ADMIN_LOGIN, self.REPO, True))
292 % (TEST_USER_ADMIN_LOGIN, self.REPO, True))
316 self._compare_ok(id_, expected, given=response.body)
293 self._compare_ok(id_, expected, given=response.body)
317
294
318 def test_api_lock_repo_lock_aquire_by_non_admin(self):
295 def test_api_lock_repo_lock_aquire_by_non_admin(self):
319 repo_name = 'api_delete_me'
296 repo_name = 'api_delete_me'
320 create_repo(repo_name, self.REPO_TYPE, owner=self.TEST_USER_LOGIN)
297 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
298 cur_user=self.TEST_USER_LOGIN)
321 try:
299 try:
322 id_, params = _build_data(self.apikey_regular, 'lock',
300 id_, params = _build_data(self.apikey_regular, 'lock',
323 repoid=repo_name,
301 repoid=repo_name,
324 locked=True)
302 locked=True)
325 response = api_call(self, params)
303 response = api_call(self, params)
326 expected = ('User `%s` set lock state for repo `%s` to `%s`'
304 expected = ('User `%s` set lock state for repo `%s` to `%s`'
327 % (self.TEST_USER_LOGIN, repo_name, True))
305 % (self.TEST_USER_LOGIN, repo_name, True))
328 self._compare_ok(id_, expected, given=response.body)
306 self._compare_ok(id_, expected, given=response.body)
329 finally:
307 finally:
330 destroy_repo(repo_name)
308 fixture.destroy_repo(repo_name)
331
309
332 def test_api_lock_repo_lock_aquire_non_admin_with_userid(self):
310 def test_api_lock_repo_lock_aquire_non_admin_with_userid(self):
333 repo_name = 'api_delete_me'
311 repo_name = 'api_delete_me'
334 create_repo(repo_name, self.REPO_TYPE, owner=self.TEST_USER_LOGIN)
312 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
313 cur_user=self.TEST_USER_LOGIN)
335 try:
314 try:
336 id_, params = _build_data(self.apikey_regular, 'lock',
315 id_, params = _build_data(self.apikey_regular, 'lock',
337 userid=TEST_USER_ADMIN_LOGIN,
316 userid=TEST_USER_ADMIN_LOGIN,
338 repoid=repo_name,
317 repoid=repo_name,
339 locked=True)
318 locked=True)
340 response = api_call(self, params)
319 response = api_call(self, params)
341 expected = 'userid is not the same as your user'
320 expected = 'userid is not the same as your user'
342 self._compare_error(id_, expected, given=response.body)
321 self._compare_error(id_, expected, given=response.body)
343 finally:
322 finally:
344 destroy_repo(repo_name)
323 fixture.destroy_repo(repo_name)
345
324
346 def test_api_lock_repo_lock_aquire_non_admin_not_his_repo(self):
325 def test_api_lock_repo_lock_aquire_non_admin_not_his_repo(self):
347 id_, params = _build_data(self.apikey_regular, 'lock',
326 id_, params = _build_data(self.apikey_regular, 'lock',
348 repoid=self.REPO,
327 repoid=self.REPO,
349 locked=True)
328 locked=True)
350 response = api_call(self, params)
329 response = api_call(self, params)
351 expected = 'repository `%s` does not exist' % (self.REPO)
330 expected = 'repository `%s` does not exist' % (self.REPO)
352 self._compare_error(id_, expected, given=response.body)
331 self._compare_error(id_, expected, given=response.body)
353
332
354 def test_api_lock_repo_lock_release(self):
333 def test_api_lock_repo_lock_release(self):
355 id_, params = _build_data(self.apikey, 'lock',
334 id_, params = _build_data(self.apikey, 'lock',
356 userid=TEST_USER_ADMIN_LOGIN,
335 userid=TEST_USER_ADMIN_LOGIN,
357 repoid=self.REPO,
336 repoid=self.REPO,
358 locked=False)
337 locked=False)
359 response = api_call(self, params)
338 response = api_call(self, params)
360 expected = ('User `%s` set lock state for repo `%s` to `%s`'
339 expected = ('User `%s` set lock state for repo `%s` to `%s`'
361 % (TEST_USER_ADMIN_LOGIN, self.REPO, False))
340 % (TEST_USER_ADMIN_LOGIN, self.REPO, False))
362 self._compare_ok(id_, expected, given=response.body)
341 self._compare_ok(id_, expected, given=response.body)
363
342
364 def test_api_lock_repo_lock_aquire_optional_userid(self):
343 def test_api_lock_repo_lock_aquire_optional_userid(self):
365 id_, params = _build_data(self.apikey, 'lock',
344 id_, params = _build_data(self.apikey, 'lock',
366 repoid=self.REPO,
345 repoid=self.REPO,
367 locked=True)
346 locked=True)
368 response = api_call(self, params)
347 response = api_call(self, params)
369 expected = ('User `%s` set lock state for repo `%s` to `%s`'
348 expected = ('User `%s` set lock state for repo `%s` to `%s`'
370 % (TEST_USER_ADMIN_LOGIN, self.REPO, True))
349 % (TEST_USER_ADMIN_LOGIN, self.REPO, True))
371 self._compare_ok(id_, expected, given=response.body)
350 self._compare_ok(id_, expected, given=response.body)
372
351
373 def test_api_lock_repo_lock_optional_locked(self):
352 def test_api_lock_repo_lock_optional_locked(self):
374 from rhodecode.lib.utils2 import time_to_datetime
353 from rhodecode.lib.utils2 import time_to_datetime
375 _locked_since = json.dumps(time_to_datetime(Repository\
354 _locked_since = json.dumps(time_to_datetime(Repository\
376 .get_by_repo_name(self.REPO).locked[1]))
355 .get_by_repo_name(self.REPO).locked[1]))
377 id_, params = _build_data(self.apikey, 'lock',
356 id_, params = _build_data(self.apikey, 'lock',
378 repoid=self.REPO)
357 repoid=self.REPO)
379 response = api_call(self, params)
358 response = api_call(self, params)
380 expected = ('Repo `%s` locked by `%s`. Locked=`True`. Locked since: `%s`'
359 expected = ('Repo `%s` locked by `%s`. Locked=`True`. Locked since: `%s`'
381 % (self.REPO, TEST_USER_ADMIN_LOGIN, _locked_since))
360 % (self.REPO, TEST_USER_ADMIN_LOGIN, _locked_since))
382 self._compare_ok(id_, expected, given=response.body)
361 self._compare_ok(id_, expected, given=response.body)
383
362
384 @mock.patch.object(Repository, 'lock', crash)
363 @mock.patch.object(Repository, 'lock', crash)
385 def test_api_lock_error(self):
364 def test_api_lock_error(self):
386 id_, params = _build_data(self.apikey, 'lock',
365 id_, params = _build_data(self.apikey, 'lock',
387 userid=TEST_USER_ADMIN_LOGIN,
366 userid=TEST_USER_ADMIN_LOGIN,
388 repoid=self.REPO,
367 repoid=self.REPO,
389 locked=True)
368 locked=True)
390 response = api_call(self, params)
369 response = api_call(self, params)
391
370
392 expected = 'Error occurred locking repository `%s`' % self.REPO
371 expected = 'Error occurred locking repository `%s`' % self.REPO
393 self._compare_error(id_, expected, given=response.body)
372 self._compare_error(id_, expected, given=response.body)
394
373
395 def test_api_get_locks_regular_user(self):
374 def test_api_get_locks_regular_user(self):
396 id_, params = _build_data(self.apikey_regular, 'get_locks')
375 id_, params = _build_data(self.apikey_regular, 'get_locks')
397 response = api_call(self, params)
376 response = api_call(self, params)
398 expected = []
377 expected = []
399 self._compare_ok(id_, expected, given=response.body)
378 self._compare_ok(id_, expected, given=response.body)
400
379
401 def test_api_get_locks_with_userid_regular_user(self):
380 def test_api_get_locks_with_userid_regular_user(self):
402 id_, params = _build_data(self.apikey_regular, 'get_locks',
381 id_, params = _build_data(self.apikey_regular, 'get_locks',
403 userid=TEST_USER_ADMIN_LOGIN)
382 userid=TEST_USER_ADMIN_LOGIN)
404 response = api_call(self, params)
383 response = api_call(self, params)
405 expected = 'userid is not the same as your user'
384 expected = 'userid is not the same as your user'
406 self._compare_error(id_, expected, given=response.body)
385 self._compare_error(id_, expected, given=response.body)
407
386
408 def test_api_get_locks(self):
387 def test_api_get_locks(self):
409 id_, params = _build_data(self.apikey, 'get_locks')
388 id_, params = _build_data(self.apikey, 'get_locks')
410 response = api_call(self, params)
389 response = api_call(self, params)
411 expected = []
390 expected = []
412 self._compare_ok(id_, expected, given=response.body)
391 self._compare_ok(id_, expected, given=response.body)
413
392
414 def test_api_get_locks_with_userid(self):
393 def test_api_get_locks_with_userid(self):
415 id_, params = _build_data(self.apikey, 'get_locks',
394 id_, params = _build_data(self.apikey, 'get_locks',
416 userid=TEST_USER_REGULAR_LOGIN)
395 userid=TEST_USER_REGULAR_LOGIN)
417 response = api_call(self, params)
396 response = api_call(self, params)
418 expected = []
397 expected = []
419 self._compare_ok(id_, expected, given=response.body)
398 self._compare_ok(id_, expected, given=response.body)
420
399
421 def test_api_create_existing_user(self):
400 def test_api_create_existing_user(self):
422 id_, params = _build_data(self.apikey, 'create_user',
401 id_, params = _build_data(self.apikey, 'create_user',
423 username=TEST_USER_ADMIN_LOGIN,
402 username=TEST_USER_ADMIN_LOGIN,
424 email='test@foo.com',
403 email='test@foo.com',
425 password='trololo')
404 password='trololo')
426 response = api_call(self, params)
405 response = api_call(self, params)
427
406
428 expected = "user `%s` already exist" % TEST_USER_ADMIN_LOGIN
407 expected = "user `%s` already exist" % TEST_USER_ADMIN_LOGIN
429 self._compare_error(id_, expected, given=response.body)
408 self._compare_error(id_, expected, given=response.body)
430
409
431 def test_api_create_user_with_existing_email(self):
410 def test_api_create_user_with_existing_email(self):
432 id_, params = _build_data(self.apikey, 'create_user',
411 id_, params = _build_data(self.apikey, 'create_user',
433 username=TEST_USER_ADMIN_LOGIN + 'new',
412 username=TEST_USER_ADMIN_LOGIN + 'new',
434 email=TEST_USER_REGULAR_EMAIL,
413 email=TEST_USER_REGULAR_EMAIL,
435 password='trololo')
414 password='trololo')
436 response = api_call(self, params)
415 response = api_call(self, params)
437
416
438 expected = "email `%s` already exist" % TEST_USER_REGULAR_EMAIL
417 expected = "email `%s` already exist" % TEST_USER_REGULAR_EMAIL
439 self._compare_error(id_, expected, given=response.body)
418 self._compare_error(id_, expected, given=response.body)
440
419
441 def test_api_create_user(self):
420 def test_api_create_user(self):
442 username = 'test_new_api_user'
421 username = 'test_new_api_user'
443 email = username + "@foo.com"
422 email = username + "@foo.com"
444
423
445 id_, params = _build_data(self.apikey, 'create_user',
424 id_, params = _build_data(self.apikey, 'create_user',
446 username=username,
425 username=username,
447 email=email,
426 email=email,
448 password='trololo')
427 password='trololo')
449 response = api_call(self, params)
428 response = api_call(self, params)
450
429
451 usr = UserModel().get_by_username(username)
430 usr = UserModel().get_by_username(username)
452 ret = dict(
431 ret = dict(
453 msg='created new user `%s`' % username,
432 msg='created new user `%s`' % username,
454 user=jsonify(usr.get_api_data())
433 user=jsonify(usr.get_api_data())
455 )
434 )
456
435
457 expected = ret
436 expected = ret
458 self._compare_ok(id_, expected, given=response.body)
437 self._compare_ok(id_, expected, given=response.body)
459
438
460 UserModel().delete(usr.user_id)
439 UserModel().delete(usr.user_id)
461 Session().commit()
440 Session().commit()
462
441
463 @mock.patch.object(UserModel, 'create_or_update', crash)
442 @mock.patch.object(UserModel, 'create_or_update', crash)
464 def test_api_create_user_when_exception_happened(self):
443 def test_api_create_user_when_exception_happened(self):
465
444
466 username = 'test_new_api_user'
445 username = 'test_new_api_user'
467 email = username + "@foo.com"
446 email = username + "@foo.com"
468
447
469 id_, params = _build_data(self.apikey, 'create_user',
448 id_, params = _build_data(self.apikey, 'create_user',
470 username=username,
449 username=username,
471 email=email,
450 email=email,
472 password='trololo')
451 password='trololo')
473 response = api_call(self, params)
452 response = api_call(self, params)
474 expected = 'failed to create user `%s`' % username
453 expected = 'failed to create user `%s`' % username
475 self._compare_error(id_, expected, given=response.body)
454 self._compare_error(id_, expected, given=response.body)
476
455
477 def test_api_delete_user(self):
456 def test_api_delete_user(self):
478 usr = UserModel().create_or_update(username=u'test_user',
457 usr = UserModel().create_or_update(username=u'test_user',
479 password=u'qweqwe',
458 password=u'qweqwe',
480 email=u'u232@rhodecode.org',
459 email=u'u232@rhodecode.org',
481 firstname=u'u1', lastname=u'u1')
460 firstname=u'u1', lastname=u'u1')
482 Session().commit()
461 Session().commit()
483 username = usr.username
462 username = usr.username
484 email = usr.email
463 email = usr.email
485 usr_id = usr.user_id
464 usr_id = usr.user_id
486 ## DELETE THIS USER NOW
465 ## DELETE THIS USER NOW
487
466
488 id_, params = _build_data(self.apikey, 'delete_user',
467 id_, params = _build_data(self.apikey, 'delete_user',
489 userid=username,)
468 userid=username,)
490 response = api_call(self, params)
469 response = api_call(self, params)
491
470
492 ret = {'msg': 'deleted user ID:%s %s' % (usr_id, username),
471 ret = {'msg': 'deleted user ID:%s %s' % (usr_id, username),
493 'user': None}
472 'user': None}
494 expected = ret
473 expected = ret
495 self._compare_ok(id_, expected, given=response.body)
474 self._compare_ok(id_, expected, given=response.body)
496
475
497 @mock.patch.object(UserModel, 'delete', crash)
476 @mock.patch.object(UserModel, 'delete', crash)
498 def test_api_delete_user_when_exception_happened(self):
477 def test_api_delete_user_when_exception_happened(self):
499 usr = UserModel().create_or_update(username=u'test_user',
478 usr = UserModel().create_or_update(username=u'test_user',
500 password=u'qweqwe',
479 password=u'qweqwe',
501 email=u'u232@rhodecode.org',
480 email=u'u232@rhodecode.org',
502 firstname=u'u1', lastname=u'u1')
481 firstname=u'u1', lastname=u'u1')
503 Session().commit()
482 Session().commit()
504 username = usr.username
483 username = usr.username
505
484
506 id_, params = _build_data(self.apikey, 'delete_user',
485 id_, params = _build_data(self.apikey, 'delete_user',
507 userid=username,)
486 userid=username,)
508 response = api_call(self, params)
487 response = api_call(self, params)
509 ret = 'failed to delete ID:%s %s' % (usr.user_id,
488 ret = 'failed to delete ID:%s %s' % (usr.user_id,
510 usr.username)
489 usr.username)
511 expected = ret
490 expected = ret
512 self._compare_error(id_, expected, given=response.body)
491 self._compare_error(id_, expected, given=response.body)
513
492
514 @parameterized.expand([('firstname', 'new_username'),
493 @parameterized.expand([('firstname', 'new_username'),
515 ('lastname', 'new_username'),
494 ('lastname', 'new_username'),
516 ('email', 'new_username'),
495 ('email', 'new_username'),
517 ('admin', True),
496 ('admin', True),
518 ('admin', False),
497 ('admin', False),
519 ('ldap_dn', 'test'),
498 ('ldap_dn', 'test'),
520 ('ldap_dn', None),
499 ('ldap_dn', None),
521 ('active', False),
500 ('active', False),
522 ('active', True),
501 ('active', True),
523 ('password', 'newpass')
502 ('password', 'newpass')
524 ])
503 ])
525 def test_api_update_user(self, name, expected):
504 def test_api_update_user(self, name, expected):
526 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
505 usr = UserModel().get_by_username(self.TEST_USER_LOGIN)
527 kw = {name: expected,
506 kw = {name: expected,
528 'userid': usr.user_id}
507 'userid': usr.user_id}
529 id_, params = _build_data(self.apikey, 'update_user', **kw)
508 id_, params = _build_data(self.apikey, 'update_user', **kw)
530 response = api_call(self, params)
509 response = api_call(self, params)
531
510
532 ret = {
511 ret = {
533 'msg': 'updated user ID:%s %s' % (usr.user_id, self.TEST_USER_LOGIN),
512 'msg': 'updated user ID:%s %s' % (usr.user_id, self.TEST_USER_LOGIN),
534 'user': jsonify(UserModel()\
513 'user': jsonify(UserModel()\
535 .get_by_username(self.TEST_USER_LOGIN)\
514 .get_by_username(self.TEST_USER_LOGIN)\
536 .get_api_data())
515 .get_api_data())
537 }
516 }
538
517
539 expected = ret
518 expected = ret
540 self._compare_ok(id_, expected, given=response.body)
519 self._compare_ok(id_, expected, given=response.body)
541
520
542 def test_api_update_user_no_changed_params(self):
521 def test_api_update_user_no_changed_params(self):
543 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
522 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
544 ret = jsonify(usr.get_api_data())
523 ret = jsonify(usr.get_api_data())
545 id_, params = _build_data(self.apikey, 'update_user',
524 id_, params = _build_data(self.apikey, 'update_user',
546 userid=TEST_USER_ADMIN_LOGIN)
525 userid=TEST_USER_ADMIN_LOGIN)
547
526
548 response = api_call(self, params)
527 response = api_call(self, params)
549 ret = {
528 ret = {
550 'msg': 'updated user ID:%s %s' % (usr.user_id, TEST_USER_ADMIN_LOGIN),
529 'msg': 'updated user ID:%s %s' % (usr.user_id, TEST_USER_ADMIN_LOGIN),
551 'user': ret
530 'user': ret
552 }
531 }
553 expected = ret
532 expected = ret
554 self._compare_ok(id_, expected, given=response.body)
533 self._compare_ok(id_, expected, given=response.body)
555
534
556 def test_api_update_user_by_user_id(self):
535 def test_api_update_user_by_user_id(self):
557 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
536 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
558 ret = jsonify(usr.get_api_data())
537 ret = jsonify(usr.get_api_data())
559 id_, params = _build_data(self.apikey, 'update_user',
538 id_, params = _build_data(self.apikey, 'update_user',
560 userid=usr.user_id)
539 userid=usr.user_id)
561
540
562 response = api_call(self, params)
541 response = api_call(self, params)
563 ret = {
542 ret = {
564 'msg': 'updated user ID:%s %s' % (usr.user_id, TEST_USER_ADMIN_LOGIN),
543 'msg': 'updated user ID:%s %s' % (usr.user_id, TEST_USER_ADMIN_LOGIN),
565 'user': ret
544 'user': ret
566 }
545 }
567 expected = ret
546 expected = ret
568 self._compare_ok(id_, expected, given=response.body)
547 self._compare_ok(id_, expected, given=response.body)
569
548
570 @mock.patch.object(UserModel, 'update_user', crash)
549 @mock.patch.object(UserModel, 'update_user', crash)
571 def test_api_update_user_when_exception_happens(self):
550 def test_api_update_user_when_exception_happens(self):
572 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
551 usr = UserModel().get_by_username(TEST_USER_ADMIN_LOGIN)
573 ret = jsonify(usr.get_api_data())
552 ret = jsonify(usr.get_api_data())
574 id_, params = _build_data(self.apikey, 'update_user',
553 id_, params = _build_data(self.apikey, 'update_user',
575 userid=usr.user_id)
554 userid=usr.user_id)
576
555
577 response = api_call(self, params)
556 response = api_call(self, params)
578 ret = 'failed to update user `%s`' % usr.user_id
557 ret = 'failed to update user `%s`' % usr.user_id
579
558
580 expected = ret
559 expected = ret
581 self._compare_error(id_, expected, given=response.body)
560 self._compare_error(id_, expected, given=response.body)
582
561
583 def test_api_get_repo(self):
562 def test_api_get_repo(self):
584 new_group = 'some_new_group'
563 new_group = 'some_new_group'
585 make_users_group(new_group)
564 make_users_group(new_group)
586 RepoModel().grant_users_group_permission(repo=self.REPO,
565 RepoModel().grant_users_group_permission(repo=self.REPO,
587 group_name=new_group,
566 group_name=new_group,
588 perm='repository.read')
567 perm='repository.read')
589 Session().commit()
568 Session().commit()
590 id_, params = _build_data(self.apikey, 'get_repo',
569 id_, params = _build_data(self.apikey, 'get_repo',
591 repoid=self.REPO)
570 repoid=self.REPO)
592 response = api_call(self, params)
571 response = api_call(self, params)
593
572
594 repo = RepoModel().get_by_repo_name(self.REPO)
573 repo = RepoModel().get_by_repo_name(self.REPO)
595 ret = repo.get_api_data()
574 ret = repo.get_api_data()
596
575
597 members = []
576 members = []
598 followers = []
577 followers = []
599 for user in repo.repo_to_perm:
578 for user in repo.repo_to_perm:
600 perm = user.permission.permission_name
579 perm = user.permission.permission_name
601 user = user.user
580 user = user.user
602 user_data = user.get_api_data()
581 user_data = user.get_api_data()
603 user_data['type'] = "user"
582 user_data['type'] = "user"
604 user_data['permission'] = perm
583 user_data['permission'] = perm
605 members.append(user_data)
584 members.append(user_data)
606
585
607 for users_group in repo.users_group_to_perm:
586 for users_group in repo.users_group_to_perm:
608 perm = users_group.permission.permission_name
587 perm = users_group.permission.permission_name
609 users_group = users_group.users_group
588 users_group = users_group.users_group
610 users_group_data = users_group.get_api_data()
589 users_group_data = users_group.get_api_data()
611 users_group_data['type'] = "users_group"
590 users_group_data['type'] = "users_group"
612 users_group_data['permission'] = perm
591 users_group_data['permission'] = perm
613 members.append(users_group_data)
592 members.append(users_group_data)
614
593
615 for user in repo.followers:
594 for user in repo.followers:
616 followers.append(user.user.get_api_data())
595 followers.append(user.user.get_api_data())
617
596
618 ret['members'] = members
597 ret['members'] = members
619 ret['followers'] = followers
598 ret['followers'] = followers
620
599
621 expected = ret
600 expected = ret
622 self._compare_ok(id_, expected, given=response.body)
601 self._compare_ok(id_, expected, given=response.body)
623 destroy_users_group(new_group)
602 destroy_users_group(new_group)
624
603
625 def test_api_get_repo_by_non_admin(self):
604 def test_api_get_repo_by_non_admin(self):
626 id_, params = _build_data(self.apikey, 'get_repo',
605 id_, params = _build_data(self.apikey, 'get_repo',
627 repoid=self.REPO)
606 repoid=self.REPO)
628 response = api_call(self, params)
607 response = api_call(self, params)
629
608
630 repo = RepoModel().get_by_repo_name(self.REPO)
609 repo = RepoModel().get_by_repo_name(self.REPO)
631 ret = repo.get_api_data()
610 ret = repo.get_api_data()
632
611
633 members = []
612 members = []
634 followers = []
613 followers = []
635 for user in repo.repo_to_perm:
614 for user in repo.repo_to_perm:
636 perm = user.permission.permission_name
615 perm = user.permission.permission_name
637 user = user.user
616 user = user.user
638 user_data = user.get_api_data()
617 user_data = user.get_api_data()
639 user_data['type'] = "user"
618 user_data['type'] = "user"
640 user_data['permission'] = perm
619 user_data['permission'] = perm
641 members.append(user_data)
620 members.append(user_data)
642
621
643 for users_group in repo.users_group_to_perm:
622 for users_group in repo.users_group_to_perm:
644 perm = users_group.permission.permission_name
623 perm = users_group.permission.permission_name
645 users_group = users_group.users_group
624 users_group = users_group.users_group
646 users_group_data = users_group.get_api_data()
625 users_group_data = users_group.get_api_data()
647 users_group_data['type'] = "users_group"
626 users_group_data['type'] = "users_group"
648 users_group_data['permission'] = perm
627 users_group_data['permission'] = perm
649 members.append(users_group_data)
628 members.append(users_group_data)
650
629
651 for user in repo.followers:
630 for user in repo.followers:
652 followers.append(user.user.get_api_data())
631 followers.append(user.user.get_api_data())
653
632
654 ret['members'] = members
633 ret['members'] = members
655 ret['followers'] = followers
634 ret['followers'] = followers
656
635
657 expected = ret
636 expected = ret
658 self._compare_ok(id_, expected, given=response.body)
637 self._compare_ok(id_, expected, given=response.body)
659
638
660 def test_api_get_repo_by_non_admin_no_permission_to_repo(self):
639 def test_api_get_repo_by_non_admin_no_permission_to_repo(self):
661 RepoModel().grant_user_permission(repo=self.REPO,
640 RepoModel().grant_user_permission(repo=self.REPO,
662 user=self.TEST_USER_LOGIN,
641 user=self.TEST_USER_LOGIN,
663 perm='repository.none')
642 perm='repository.none')
664
643
665 id_, params = _build_data(self.apikey_regular, 'get_repo',
644 id_, params = _build_data(self.apikey_regular, 'get_repo',
666 repoid=self.REPO)
645 repoid=self.REPO)
667 response = api_call(self, params)
646 response = api_call(self, params)
668
647
669 expected = 'repository `%s` does not exist' % (self.REPO)
648 expected = 'repository `%s` does not exist' % (self.REPO)
670 self._compare_error(id_, expected, given=response.body)
649 self._compare_error(id_, expected, given=response.body)
671
650
672 def test_api_get_repo_that_doesn_not_exist(self):
651 def test_api_get_repo_that_doesn_not_exist(self):
673 id_, params = _build_data(self.apikey, 'get_repo',
652 id_, params = _build_data(self.apikey, 'get_repo',
674 repoid='no-such-repo')
653 repoid='no-such-repo')
675 response = api_call(self, params)
654 response = api_call(self, params)
676
655
677 ret = 'repository `%s` does not exist' % 'no-such-repo'
656 ret = 'repository `%s` does not exist' % 'no-such-repo'
678 expected = ret
657 expected = ret
679 self._compare_error(id_, expected, given=response.body)
658 self._compare_error(id_, expected, given=response.body)
680
659
681 def test_api_get_repos(self):
660 def test_api_get_repos(self):
682 id_, params = _build_data(self.apikey, 'get_repos')
661 id_, params = _build_data(self.apikey, 'get_repos')
683 response = api_call(self, params)
662 response = api_call(self, params)
684
663
685 result = []
664 result = []
686 for repo in RepoModel().get_all():
665 for repo in RepoModel().get_all():
687 result.append(repo.get_api_data())
666 result.append(repo.get_api_data())
688 ret = jsonify(result)
667 ret = jsonify(result)
689
668
690 expected = ret
669 expected = ret
691 self._compare_ok(id_, expected, given=response.body)
670 self._compare_ok(id_, expected, given=response.body)
692
671
693 def test_api_get_repos_non_admin(self):
672 def test_api_get_repos_non_admin(self):
694 id_, params = _build_data(self.apikey_regular, 'get_repos')
673 id_, params = _build_data(self.apikey_regular, 'get_repos')
695 response = api_call(self, params)
674 response = api_call(self, params)
696
675
697 result = []
676 result = []
698 for repo in RepoModel().get_all_user_repos(self.TEST_USER_LOGIN):
677 for repo in RepoModel().get_all_user_repos(self.TEST_USER_LOGIN):
699 result.append(repo.get_api_data())
678 result.append(repo.get_api_data())
700 ret = jsonify(result)
679 ret = jsonify(result)
701
680
702 expected = ret
681 expected = ret
703 self._compare_ok(id_, expected, given=response.body)
682 self._compare_ok(id_, expected, given=response.body)
704
683
705 @parameterized.expand([('all', 'all'),
684 @parameterized.expand([('all', 'all'),
706 ('dirs', 'dirs'),
685 ('dirs', 'dirs'),
707 ('files', 'files'), ])
686 ('files', 'files'), ])
708 def test_api_get_repo_nodes(self, name, ret_type):
687 def test_api_get_repo_nodes(self, name, ret_type):
709 rev = 'tip'
688 rev = 'tip'
710 path = '/'
689 path = '/'
711 id_, params = _build_data(self.apikey, 'get_repo_nodes',
690 id_, params = _build_data(self.apikey, 'get_repo_nodes',
712 repoid=self.REPO, revision=rev,
691 repoid=self.REPO, revision=rev,
713 root_path=path,
692 root_path=path,
714 ret_type=ret_type)
693 ret_type=ret_type)
715 response = api_call(self, params)
694 response = api_call(self, params)
716
695
717 # we don't the actual return types here since it's tested somewhere
696 # we don't the actual return types here since it's tested somewhere
718 # else
697 # else
719 expected = json.loads(response.body)['result']
698 expected = json.loads(response.body)['result']
720 self._compare_ok(id_, expected, given=response.body)
699 self._compare_ok(id_, expected, given=response.body)
721
700
722 def test_api_get_repo_nodes_bad_revisions(self):
701 def test_api_get_repo_nodes_bad_revisions(self):
723 rev = 'i-dont-exist'
702 rev = 'i-dont-exist'
724 path = '/'
703 path = '/'
725 id_, params = _build_data(self.apikey, 'get_repo_nodes',
704 id_, params = _build_data(self.apikey, 'get_repo_nodes',
726 repoid=self.REPO, revision=rev,
705 repoid=self.REPO, revision=rev,
727 root_path=path,)
706 root_path=path,)
728 response = api_call(self, params)
707 response = api_call(self, params)
729
708
730 expected = 'failed to get repo: `%s` nodes' % self.REPO
709 expected = 'failed to get repo: `%s` nodes' % self.REPO
731 self._compare_error(id_, expected, given=response.body)
710 self._compare_error(id_, expected, given=response.body)
732
711
733 def test_api_get_repo_nodes_bad_path(self):
712 def test_api_get_repo_nodes_bad_path(self):
734 rev = 'tip'
713 rev = 'tip'
735 path = '/idontexits'
714 path = '/idontexits'
736 id_, params = _build_data(self.apikey, 'get_repo_nodes',
715 id_, params = _build_data(self.apikey, 'get_repo_nodes',
737 repoid=self.REPO, revision=rev,
716 repoid=self.REPO, revision=rev,
738 root_path=path,)
717 root_path=path,)
739 response = api_call(self, params)
718 response = api_call(self, params)
740
719
741 expected = 'failed to get repo: `%s` nodes' % self.REPO
720 expected = 'failed to get repo: `%s` nodes' % self.REPO
742 self._compare_error(id_, expected, given=response.body)
721 self._compare_error(id_, expected, given=response.body)
743
722
744 def test_api_get_repo_nodes_bad_ret_type(self):
723 def test_api_get_repo_nodes_bad_ret_type(self):
745 rev = 'tip'
724 rev = 'tip'
746 path = '/'
725 path = '/'
747 ret_type = 'error'
726 ret_type = 'error'
748 id_, params = _build_data(self.apikey, 'get_repo_nodes',
727 id_, params = _build_data(self.apikey, 'get_repo_nodes',
749 repoid=self.REPO, revision=rev,
728 repoid=self.REPO, revision=rev,
750 root_path=path,
729 root_path=path,
751 ret_type=ret_type)
730 ret_type=ret_type)
752 response = api_call(self, params)
731 response = api_call(self, params)
753
732
754 expected = 'ret_type must be one of %s' % (['files', 'dirs', 'all'])
733 expected = 'ret_type must be one of %s' % (['files', 'dirs', 'all'])
755 self._compare_error(id_, expected, given=response.body)
734 self._compare_error(id_, expected, given=response.body)
756
735
757 def test_api_create_repo(self):
736 def test_api_create_repo(self):
758 repo_name = 'api-repo'
737 repo_name = 'api-repo'
759 id_, params = _build_data(self.apikey, 'create_repo',
738 id_, params = _build_data(self.apikey, 'create_repo',
760 repo_name=repo_name,
739 repo_name=repo_name,
761 owner=TEST_USER_ADMIN_LOGIN,
740 owner=TEST_USER_ADMIN_LOGIN,
762 repo_type='hg',
741 repo_type='hg',
763 )
742 )
764 response = api_call(self, params)
743 response = api_call(self, params)
765
744
766 repo = RepoModel().get_by_repo_name(repo_name)
745 repo = RepoModel().get_by_repo_name(repo_name)
767 ret = {
746 ret = {
768 'msg': 'Created new repository `%s`' % repo_name,
747 'msg': 'Created new repository `%s`' % repo_name,
769 'repo': jsonify(repo.get_api_data())
748 'repo': jsonify(repo.get_api_data())
770 }
749 }
771 expected = ret
750 expected = ret
772 self._compare_ok(id_, expected, given=response.body)
751 self._compare_ok(id_, expected, given=response.body)
773 destroy_repo(repo_name)
752 fixture.destroy_repo(repo_name)
774
753
775 def test_api_create_repo_unknown_owner(self):
754 def test_api_create_repo_unknown_owner(self):
776 repo_name = 'api-repo'
755 repo_name = 'api-repo'
777 owner = 'i-dont-exist'
756 owner = 'i-dont-exist'
778 id_, params = _build_data(self.apikey, 'create_repo',
757 id_, params = _build_data(self.apikey, 'create_repo',
779 repo_name=repo_name,
758 repo_name=repo_name,
780 owner=owner,
759 owner=owner,
781 repo_type='hg',
760 repo_type='hg',
782 )
761 )
783 response = api_call(self, params)
762 response = api_call(self, params)
784 expected = 'user `%s` does not exist' % owner
763 expected = 'user `%s` does not exist' % owner
785 self._compare_error(id_, expected, given=response.body)
764 self._compare_error(id_, expected, given=response.body)
786
765
787 def test_api_create_repo_dont_specify_owner(self):
766 def test_api_create_repo_dont_specify_owner(self):
788 repo_name = 'api-repo'
767 repo_name = 'api-repo'
789 owner = 'i-dont-exist'
768 owner = 'i-dont-exist'
790 id_, params = _build_data(self.apikey, 'create_repo',
769 id_, params = _build_data(self.apikey, 'create_repo',
791 repo_name=repo_name,
770 repo_name=repo_name,
792 repo_type='hg',
771 repo_type='hg',
793 )
772 )
794 response = api_call(self, params)
773 response = api_call(self, params)
795
774
796 repo = RepoModel().get_by_repo_name(repo_name)
775 repo = RepoModel().get_by_repo_name(repo_name)
797 ret = {
776 ret = {
798 'msg': 'Created new repository `%s`' % repo_name,
777 'msg': 'Created new repository `%s`' % repo_name,
799 'repo': jsonify(repo.get_api_data())
778 'repo': jsonify(repo.get_api_data())
800 }
779 }
801 expected = ret
780 expected = ret
802 self._compare_ok(id_, expected, given=response.body)
781 self._compare_ok(id_, expected, given=response.body)
803 destroy_repo(repo_name)
782 fixture.destroy_repo(repo_name)
804
783
805 def test_api_create_repo_by_non_admin(self):
784 def test_api_create_repo_by_non_admin(self):
806 repo_name = 'api-repo'
785 repo_name = 'api-repo'
807 owner = 'i-dont-exist'
786 owner = 'i-dont-exist'
808 id_, params = _build_data(self.apikey_regular, 'create_repo',
787 id_, params = _build_data(self.apikey_regular, 'create_repo',
809 repo_name=repo_name,
788 repo_name=repo_name,
810 repo_type='hg',
789 repo_type='hg',
811 )
790 )
812 response = api_call(self, params)
791 response = api_call(self, params)
813
792
814 repo = RepoModel().get_by_repo_name(repo_name)
793 repo = RepoModel().get_by_repo_name(repo_name)
815 ret = {
794 ret = {
816 'msg': 'Created new repository `%s`' % repo_name,
795 'msg': 'Created new repository `%s`' % repo_name,
817 'repo': jsonify(repo.get_api_data())
796 'repo': jsonify(repo.get_api_data())
818 }
797 }
819 expected = ret
798 expected = ret
820 self._compare_ok(id_, expected, given=response.body)
799 self._compare_ok(id_, expected, given=response.body)
821 destroy_repo(repo_name)
800 fixture.destroy_repo(repo_name)
822
801
823 def test_api_create_repo_by_non_admin_specify_owner(self):
802 def test_api_create_repo_by_non_admin_specify_owner(self):
824 repo_name = 'api-repo'
803 repo_name = 'api-repo'
825 owner = 'i-dont-exist'
804 owner = 'i-dont-exist'
826 id_, params = _build_data(self.apikey_regular, 'create_repo',
805 id_, params = _build_data(self.apikey_regular, 'create_repo',
827 repo_name=repo_name,
806 repo_name=repo_name,
828 repo_type='hg',
807 repo_type='hg',
829 owner=owner
808 owner=owner
830 )
809 )
831 response = api_call(self, params)
810 response = api_call(self, params)
832
811
833 expected = 'Only RhodeCode admin can specify `owner` param'
812 expected = 'Only RhodeCode admin can specify `owner` param'
834 self._compare_error(id_, expected, given=response.body)
813 self._compare_error(id_, expected, given=response.body)
835 destroy_repo(repo_name)
814 fixture.destroy_repo(repo_name)
836
815
837 def test_api_create_repo_exists(self):
816 def test_api_create_repo_exists(self):
838 repo_name = self.REPO
817 repo_name = self.REPO
839 id_, params = _build_data(self.apikey, 'create_repo',
818 id_, params = _build_data(self.apikey, 'create_repo',
840 repo_name=repo_name,
819 repo_name=repo_name,
841 owner=TEST_USER_ADMIN_LOGIN,
820 owner=TEST_USER_ADMIN_LOGIN,
842 repo_type='hg',
821 repo_type='hg',
843 )
822 )
844 response = api_call(self, params)
823 response = api_call(self, params)
845 expected = "repo `%s` already exist" % repo_name
824 expected = "repo `%s` already exist" % repo_name
846 self._compare_error(id_, expected, given=response.body)
825 self._compare_error(id_, expected, given=response.body)
847
826
848 @mock.patch.object(RepoModel, 'create_repo', crash)
827 @mock.patch.object(RepoModel, 'create_repo', crash)
849 def test_api_create_repo_exception_occurred(self):
828 def test_api_create_repo_exception_occurred(self):
850 repo_name = 'api-repo'
829 repo_name = 'api-repo'
851 id_, params = _build_data(self.apikey, 'create_repo',
830 id_, params = _build_data(self.apikey, 'create_repo',
852 repo_name=repo_name,
831 repo_name=repo_name,
853 owner=TEST_USER_ADMIN_LOGIN,
832 owner=TEST_USER_ADMIN_LOGIN,
854 repo_type='hg',
833 repo_type='hg',
855 )
834 )
856 response = api_call(self, params)
835 response = api_call(self, params)
857 expected = 'failed to create repository `%s`' % repo_name
836 expected = 'failed to create repository `%s`' % repo_name
858 self._compare_error(id_, expected, given=response.body)
837 self._compare_error(id_, expected, given=response.body)
859
838
860 def test_api_delete_repo(self):
839 def test_api_delete_repo(self):
861 repo_name = 'api_delete_me'
840 repo_name = 'api_delete_me'
862 create_repo(repo_name, self.REPO_TYPE)
841 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
863
842
864 id_, params = _build_data(self.apikey, 'delete_repo',
843 id_, params = _build_data(self.apikey, 'delete_repo',
865 repoid=repo_name,)
844 repoid=repo_name,)
866 response = api_call(self, params)
845 response = api_call(self, params)
867
846
868 ret = {
847 ret = {
869 'msg': 'Deleted repository `%s`' % repo_name,
848 'msg': 'Deleted repository `%s`' % repo_name,
870 'success': True
849 'success': True
871 }
850 }
872 expected = ret
851 expected = ret
873 self._compare_ok(id_, expected, given=response.body)
852 self._compare_ok(id_, expected, given=response.body)
874
853
875 def test_api_delete_repo_by_non_admin(self):
854 def test_api_delete_repo_by_non_admin(self):
876 repo_name = 'api_delete_me'
855 repo_name = 'api_delete_me'
877 create_repo(repo_name, self.REPO_TYPE, owner=self.TEST_USER_LOGIN)
856 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE,
857 cur_user=self.TEST_USER_LOGIN)
878 try:
858 try:
879 id_, params = _build_data(self.apikey_regular, 'delete_repo',
859 id_, params = _build_data(self.apikey_regular, 'delete_repo',
880 repoid=repo_name,)
860 repoid=repo_name,)
881 response = api_call(self, params)
861 response = api_call(self, params)
882
862
883 ret = {
863 ret = {
884 'msg': 'Deleted repository `%s`' % repo_name,
864 'msg': 'Deleted repository `%s`' % repo_name,
885 'success': True
865 'success': True
886 }
866 }
887 expected = ret
867 expected = ret
888 self._compare_ok(id_, expected, given=response.body)
868 self._compare_ok(id_, expected, given=response.body)
889 finally:
869 finally:
890 destroy_repo(repo_name)
870 fixture.destroy_repo(repo_name)
891
871
892 def test_api_delete_repo_by_non_admin_no_permission(self):
872 def test_api_delete_repo_by_non_admin_no_permission(self):
893 repo_name = 'api_delete_me'
873 repo_name = 'api_delete_me'
894 create_repo(repo_name, self.REPO_TYPE)
874 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
895 try:
875 try:
896 id_, params = _build_data(self.apikey_regular, 'delete_repo',
876 id_, params = _build_data(self.apikey_regular, 'delete_repo',
897 repoid=repo_name,)
877 repoid=repo_name,)
898 response = api_call(self, params)
878 response = api_call(self, params)
899 expected = 'repository `%s` does not exist' % (repo_name)
879 expected = 'repository `%s` does not exist' % (repo_name)
900 self._compare_error(id_, expected, given=response.body)
880 self._compare_error(id_, expected, given=response.body)
901 finally:
881 finally:
902 destroy_repo(repo_name)
882 fixture.destroy_repo(repo_name)
903
883
904 def test_api_delete_repo_exception_occurred(self):
884 def test_api_delete_repo_exception_occurred(self):
905 repo_name = 'api_delete_me'
885 repo_name = 'api_delete_me'
906 create_repo(repo_name, self.REPO_TYPE)
886 fixture.create_repo(repo_name, repo_type=self.REPO_TYPE)
907 try:
887 try:
908 with mock.patch.object(RepoModel, 'delete', crash):
888 with mock.patch.object(RepoModel, 'delete', crash):
909 id_, params = _build_data(self.apikey, 'delete_repo',
889 id_, params = _build_data(self.apikey, 'delete_repo',
910 repoid=repo_name,)
890 repoid=repo_name,)
911 response = api_call(self, params)
891 response = api_call(self, params)
912
892
913 expected = 'failed to delete repository `%s`' % repo_name
893 expected = 'failed to delete repository `%s`' % repo_name
914 self._compare_error(id_, expected, given=response.body)
894 self._compare_error(id_, expected, given=response.body)
915 finally:
895 finally:
916 destroy_repo(repo_name)
896 fixture.destroy_repo(repo_name)
917
897
918 def test_api_fork_repo(self):
898 def test_api_fork_repo(self):
919 fork_name = 'api-repo-fork'
899 fork_name = 'api-repo-fork'
920 id_, params = _build_data(self.apikey, 'fork_repo',
900 id_, params = _build_data(self.apikey, 'fork_repo',
921 repoid=self.REPO,
901 repoid=self.REPO,
922 fork_name=fork_name,
902 fork_name=fork_name,
923 owner=TEST_USER_ADMIN_LOGIN,
903 owner=TEST_USER_ADMIN_LOGIN,
924 )
904 )
925 response = api_call(self, params)
905 response = api_call(self, params)
926
906
927 ret = {
907 ret = {
928 'msg': 'Created fork of `%s` as `%s`' % (self.REPO,
908 'msg': 'Created fork of `%s` as `%s`' % (self.REPO,
929 fork_name),
909 fork_name),
930 'success': True
910 'success': True
931 }
911 }
932 expected = ret
912 expected = ret
933 self._compare_ok(id_, expected, given=response.body)
913 self._compare_ok(id_, expected, given=response.body)
934 destroy_repo(fork_name)
914 fixture.destroy_repo(fork_name)
935
915
936 def test_api_fork_repo_non_admin(self):
916 def test_api_fork_repo_non_admin(self):
937 fork_name = 'api-repo-fork'
917 fork_name = 'api-repo-fork'
938 id_, params = _build_data(self.apikey_regular, 'fork_repo',
918 id_, params = _build_data(self.apikey_regular, 'fork_repo',
939 repoid=self.REPO,
919 repoid=self.REPO,
940 fork_name=fork_name,
920 fork_name=fork_name,
941 )
921 )
942 response = api_call(self, params)
922 response = api_call(self, params)
943
923
944 ret = {
924 ret = {
945 'msg': 'Created fork of `%s` as `%s`' % (self.REPO,
925 'msg': 'Created fork of `%s` as `%s`' % (self.REPO,
946 fork_name),
926 fork_name),
947 'success': True
927 'success': True
948 }
928 }
949 expected = ret
929 expected = ret
950 self._compare_ok(id_, expected, given=response.body)
930 self._compare_ok(id_, expected, given=response.body)
951 destroy_repo(fork_name)
931 fixture.destroy_repo(fork_name)
952
932
953 def test_api_fork_repo_non_admin_specify_owner(self):
933 def test_api_fork_repo_non_admin_specify_owner(self):
954 fork_name = 'api-repo-fork'
934 fork_name = 'api-repo-fork'
955 id_, params = _build_data(self.apikey_regular, 'fork_repo',
935 id_, params = _build_data(self.apikey_regular, 'fork_repo',
956 repoid=self.REPO,
936 repoid=self.REPO,
957 fork_name=fork_name,
937 fork_name=fork_name,
958 owner=TEST_USER_ADMIN_LOGIN,
938 owner=TEST_USER_ADMIN_LOGIN,
959 )
939 )
960 response = api_call(self, params)
940 response = api_call(self, params)
961 expected = 'Only RhodeCode admin can specify `owner` param'
941 expected = 'Only RhodeCode admin can specify `owner` param'
962 self._compare_error(id_, expected, given=response.body)
942 self._compare_error(id_, expected, given=response.body)
963 destroy_repo(fork_name)
943 fixture.destroy_repo(fork_name)
964
944
965 def test_api_fork_repo_non_admin_no_permission_to_fork(self):
945 def test_api_fork_repo_non_admin_no_permission_to_fork(self):
966 RepoModel().grant_user_permission(repo=self.REPO,
946 RepoModel().grant_user_permission(repo=self.REPO,
967 user=self.TEST_USER_LOGIN,
947 user=self.TEST_USER_LOGIN,
968 perm='repository.none')
948 perm='repository.none')
969 fork_name = 'api-repo-fork'
949 fork_name = 'api-repo-fork'
970 id_, params = _build_data(self.apikey_regular, 'fork_repo',
950 id_, params = _build_data(self.apikey_regular, 'fork_repo',
971 repoid=self.REPO,
951 repoid=self.REPO,
972 fork_name=fork_name,
952 fork_name=fork_name,
973 )
953 )
974 response = api_call(self, params)
954 response = api_call(self, params)
975 expected = 'repository `%s` does not exist' % (self.REPO)
955 expected = 'repository `%s` does not exist' % (self.REPO)
976 self._compare_error(id_, expected, given=response.body)
956 self._compare_error(id_, expected, given=response.body)
977 destroy_repo(fork_name)
957 fixture.destroy_repo(fork_name)
978
958
979 def test_api_fork_repo_unknown_owner(self):
959 def test_api_fork_repo_unknown_owner(self):
980 fork_name = 'api-repo-fork'
960 fork_name = 'api-repo-fork'
981 owner = 'i-dont-exist'
961 owner = 'i-dont-exist'
982 id_, params = _build_data(self.apikey, 'fork_repo',
962 id_, params = _build_data(self.apikey, 'fork_repo',
983 repoid=self.REPO,
963 repoid=self.REPO,
984 fork_name=fork_name,
964 fork_name=fork_name,
985 owner=owner,
965 owner=owner,
986 )
966 )
987 response = api_call(self, params)
967 response = api_call(self, params)
988 expected = 'user `%s` does not exist' % owner
968 expected = 'user `%s` does not exist' % owner
989 self._compare_error(id_, expected, given=response.body)
969 self._compare_error(id_, expected, given=response.body)
990
970
991 def test_api_fork_repo_fork_exists(self):
971 def test_api_fork_repo_fork_exists(self):
992 fork_name = 'api-repo-fork'
972 fork_name = 'api-repo-fork'
993 create_fork(fork_name, self.REPO_TYPE, self.REPO)
973 fixture.create_fork(self.REPO, fork_name)
994
974
995 try:
975 try:
996 fork_name = 'api-repo-fork'
976 fork_name = 'api-repo-fork'
997
977
998 id_, params = _build_data(self.apikey, 'fork_repo',
978 id_, params = _build_data(self.apikey, 'fork_repo',
999 repoid=self.REPO,
979 repoid=self.REPO,
1000 fork_name=fork_name,
980 fork_name=fork_name,
1001 owner=TEST_USER_ADMIN_LOGIN,
981 owner=TEST_USER_ADMIN_LOGIN,
1002 )
982 )
1003 response = api_call(self, params)
983 response = api_call(self, params)
1004
984
1005 expected = "fork `%s` already exist" % fork_name
985 expected = "fork `%s` already exist" % fork_name
1006 self._compare_error(id_, expected, given=response.body)
986 self._compare_error(id_, expected, given=response.body)
1007 finally:
987 finally:
1008 destroy_repo(fork_name)
988 fixture.destroy_repo(fork_name)
1009
989
1010 def test_api_fork_repo_repo_exists(self):
990 def test_api_fork_repo_repo_exists(self):
1011 fork_name = self.REPO
991 fork_name = self.REPO
1012
992
1013 id_, params = _build_data(self.apikey, 'fork_repo',
993 id_, params = _build_data(self.apikey, 'fork_repo',
1014 repoid=self.REPO,
994 repoid=self.REPO,
1015 fork_name=fork_name,
995 fork_name=fork_name,
1016 owner=TEST_USER_ADMIN_LOGIN,
996 owner=TEST_USER_ADMIN_LOGIN,
1017 )
997 )
1018 response = api_call(self, params)
998 response = api_call(self, params)
1019
999
1020 expected = "repo `%s` already exist" % fork_name
1000 expected = "repo `%s` already exist" % fork_name
1021 self._compare_error(id_, expected, given=response.body)
1001 self._compare_error(id_, expected, given=response.body)
1022
1002
1023 @mock.patch.object(RepoModel, 'create_fork', crash)
1003 @mock.patch.object(RepoModel, 'create_fork', crash)
1024 def test_api_fork_repo_exception_occurred(self):
1004 def test_api_fork_repo_exception_occurred(self):
1025 fork_name = 'api-repo-fork'
1005 fork_name = 'api-repo-fork'
1026 id_, params = _build_data(self.apikey, 'fork_repo',
1006 id_, params = _build_data(self.apikey, 'fork_repo',
1027 repoid=self.REPO,
1007 repoid=self.REPO,
1028 fork_name=fork_name,
1008 fork_name=fork_name,
1029 owner=TEST_USER_ADMIN_LOGIN,
1009 owner=TEST_USER_ADMIN_LOGIN,
1030 )
1010 )
1031 response = api_call(self, params)
1011 response = api_call(self, params)
1032
1012
1033 expected = 'failed to fork repository `%s` as `%s`' % (self.REPO,
1013 expected = 'failed to fork repository `%s` as `%s`' % (self.REPO,
1034 fork_name)
1014 fork_name)
1035 self._compare_error(id_, expected, given=response.body)
1015 self._compare_error(id_, expected, given=response.body)
1036
1016
1037 def test_api_get_users_group(self):
1017 def test_api_get_users_group(self):
1038 id_, params = _build_data(self.apikey, 'get_users_group',
1018 id_, params = _build_data(self.apikey, 'get_users_group',
1039 usersgroupid=TEST_USER_GROUP)
1019 usersgroupid=TEST_USER_GROUP)
1040 response = api_call(self, params)
1020 response = api_call(self, params)
1041
1021
1042 users_group = UserGroupModel().get_group(TEST_USER_GROUP)
1022 users_group = UserGroupModel().get_group(TEST_USER_GROUP)
1043 members = []
1023 members = []
1044 for user in users_group.members:
1024 for user in users_group.members:
1045 user = user.user
1025 user = user.user
1046 members.append(user.get_api_data())
1026 members.append(user.get_api_data())
1047
1027
1048 ret = users_group.get_api_data()
1028 ret = users_group.get_api_data()
1049 ret['members'] = members
1029 ret['members'] = members
1050 expected = ret
1030 expected = ret
1051 self._compare_ok(id_, expected, given=response.body)
1031 self._compare_ok(id_, expected, given=response.body)
1052
1032
1053 def test_api_get_users_groups(self):
1033 def test_api_get_users_groups(self):
1054
1034
1055 make_users_group('test_users_group2')
1035 make_users_group('test_users_group2')
1056
1036
1057 id_, params = _build_data(self.apikey, 'get_users_groups',)
1037 id_, params = _build_data(self.apikey, 'get_users_groups',)
1058 response = api_call(self, params)
1038 response = api_call(self, params)
1059
1039
1060 expected = []
1040 expected = []
1061 for gr_name in [TEST_USER_GROUP, 'test_users_group2']:
1041 for gr_name in [TEST_USER_GROUP, 'test_users_group2']:
1062 users_group = UserGroupModel().get_group(gr_name)
1042 users_group = UserGroupModel().get_group(gr_name)
1063 ret = users_group.get_api_data()
1043 ret = users_group.get_api_data()
1064 expected.append(ret)
1044 expected.append(ret)
1065 self._compare_ok(id_, expected, given=response.body)
1045 self._compare_ok(id_, expected, given=response.body)
1066
1046
1067 UserGroupModel().delete(users_group='test_users_group2')
1047 UserGroupModel().delete(users_group='test_users_group2')
1068 Session().commit()
1048 Session().commit()
1069
1049
1070 def test_api_create_users_group(self):
1050 def test_api_create_users_group(self):
1071 group_name = 'some_new_group'
1051 group_name = 'some_new_group'
1072 id_, params = _build_data(self.apikey, 'create_users_group',
1052 id_, params = _build_data(self.apikey, 'create_users_group',
1073 group_name=group_name)
1053 group_name=group_name)
1074 response = api_call(self, params)
1054 response = api_call(self, params)
1075
1055
1076 ret = {
1056 ret = {
1077 'msg': 'created new user group `%s`' % group_name,
1057 'msg': 'created new user group `%s`' % group_name,
1078 'users_group': jsonify(UserGroupModel()\
1058 'users_group': jsonify(UserGroupModel()\
1079 .get_by_name(group_name)\
1059 .get_by_name(group_name)\
1080 .get_api_data())
1060 .get_api_data())
1081 }
1061 }
1082 expected = ret
1062 expected = ret
1083 self._compare_ok(id_, expected, given=response.body)
1063 self._compare_ok(id_, expected, given=response.body)
1084
1064
1085 destroy_users_group(group_name)
1065 destroy_users_group(group_name)
1086
1066
1087 def test_api_get_users_group_that_exist(self):
1067 def test_api_get_users_group_that_exist(self):
1088 id_, params = _build_data(self.apikey, 'create_users_group',
1068 id_, params = _build_data(self.apikey, 'create_users_group',
1089 group_name=TEST_USER_GROUP)
1069 group_name=TEST_USER_GROUP)
1090 response = api_call(self, params)
1070 response = api_call(self, params)
1091
1071
1092 expected = "user group `%s` already exist" % TEST_USER_GROUP
1072 expected = "user group `%s` already exist" % TEST_USER_GROUP
1093 self._compare_error(id_, expected, given=response.body)
1073 self._compare_error(id_, expected, given=response.body)
1094
1074
1095 @mock.patch.object(UserGroupModel, 'create', crash)
1075 @mock.patch.object(UserGroupModel, 'create', crash)
1096 def test_api_get_users_group_exception_occurred(self):
1076 def test_api_get_users_group_exception_occurred(self):
1097 group_name = 'exception_happens'
1077 group_name = 'exception_happens'
1098 id_, params = _build_data(self.apikey, 'create_users_group',
1078 id_, params = _build_data(self.apikey, 'create_users_group',
1099 group_name=group_name)
1079 group_name=group_name)
1100 response = api_call(self, params)
1080 response = api_call(self, params)
1101
1081
1102 expected = 'failed to create group `%s`' % group_name
1082 expected = 'failed to create group `%s`' % group_name
1103 self._compare_error(id_, expected, given=response.body)
1083 self._compare_error(id_, expected, given=response.body)
1104
1084
1105 def test_api_add_user_to_users_group(self):
1085 def test_api_add_user_to_users_group(self):
1106 gr_name = 'test_group'
1086 gr_name = 'test_group'
1107 UserGroupModel().create(gr_name)
1087 UserGroupModel().create(gr_name)
1108 Session().commit()
1088 Session().commit()
1109 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1089 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1110 usersgroupid=gr_name,
1090 usersgroupid=gr_name,
1111 userid=TEST_USER_ADMIN_LOGIN)
1091 userid=TEST_USER_ADMIN_LOGIN)
1112 response = api_call(self, params)
1092 response = api_call(self, params)
1113
1093
1114 expected = {
1094 expected = {
1115 'msg': 'added member `%s` to user group `%s`' % (
1095 'msg': 'added member `%s` to user group `%s`' % (
1116 TEST_USER_ADMIN_LOGIN, gr_name
1096 TEST_USER_ADMIN_LOGIN, gr_name
1117 ),
1097 ),
1118 'success': True}
1098 'success': True}
1119 self._compare_ok(id_, expected, given=response.body)
1099 self._compare_ok(id_, expected, given=response.body)
1120
1100
1121 UserGroupModel().delete(users_group=gr_name)
1101 UserGroupModel().delete(users_group=gr_name)
1122 Session().commit()
1102 Session().commit()
1123
1103
1124 def test_api_add_user_to_users_group_that_doesnt_exist(self):
1104 def test_api_add_user_to_users_group_that_doesnt_exist(self):
1125 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1105 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1126 usersgroupid='false-group',
1106 usersgroupid='false-group',
1127 userid=TEST_USER_ADMIN_LOGIN)
1107 userid=TEST_USER_ADMIN_LOGIN)
1128 response = api_call(self, params)
1108 response = api_call(self, params)
1129
1109
1130 expected = 'user group `%s` does not exist' % 'false-group'
1110 expected = 'user group `%s` does not exist' % 'false-group'
1131 self._compare_error(id_, expected, given=response.body)
1111 self._compare_error(id_, expected, given=response.body)
1132
1112
1133 @mock.patch.object(UserGroupModel, 'add_user_to_group', crash)
1113 @mock.patch.object(UserGroupModel, 'add_user_to_group', crash)
1134 def test_api_add_user_to_users_group_exception_occurred(self):
1114 def test_api_add_user_to_users_group_exception_occurred(self):
1135 gr_name = 'test_group'
1115 gr_name = 'test_group'
1136 UserGroupModel().create(gr_name)
1116 UserGroupModel().create(gr_name)
1137 Session().commit()
1117 Session().commit()
1138 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1118 id_, params = _build_data(self.apikey, 'add_user_to_users_group',
1139 usersgroupid=gr_name,
1119 usersgroupid=gr_name,
1140 userid=TEST_USER_ADMIN_LOGIN)
1120 userid=TEST_USER_ADMIN_LOGIN)
1141 response = api_call(self, params)
1121 response = api_call(self, params)
1142
1122
1143 expected = 'failed to add member to user group `%s`' % gr_name
1123 expected = 'failed to add member to user group `%s`' % gr_name
1144 self._compare_error(id_, expected, given=response.body)
1124 self._compare_error(id_, expected, given=response.body)
1145
1125
1146 UserGroupModel().delete(users_group=gr_name)
1126 UserGroupModel().delete(users_group=gr_name)
1147 Session().commit()
1127 Session().commit()
1148
1128
1149 def test_api_remove_user_from_users_group(self):
1129 def test_api_remove_user_from_users_group(self):
1150 gr_name = 'test_group_3'
1130 gr_name = 'test_group_3'
1151 gr = UserGroupModel().create(gr_name)
1131 gr = UserGroupModel().create(gr_name)
1152 UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
1132 UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
1153 Session().commit()
1133 Session().commit()
1154 id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
1134 id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
1155 usersgroupid=gr_name,
1135 usersgroupid=gr_name,
1156 userid=TEST_USER_ADMIN_LOGIN)
1136 userid=TEST_USER_ADMIN_LOGIN)
1157 response = api_call(self, params)
1137 response = api_call(self, params)
1158
1138
1159 expected = {
1139 expected = {
1160 'msg': 'removed member `%s` from user group `%s`' % (
1140 'msg': 'removed member `%s` from user group `%s`' % (
1161 TEST_USER_ADMIN_LOGIN, gr_name
1141 TEST_USER_ADMIN_LOGIN, gr_name
1162 ),
1142 ),
1163 'success': True}
1143 'success': True}
1164 self._compare_ok(id_, expected, given=response.body)
1144 self._compare_ok(id_, expected, given=response.body)
1165
1145
1166 UserGroupModel().delete(users_group=gr_name)
1146 UserGroupModel().delete(users_group=gr_name)
1167 Session().commit()
1147 Session().commit()
1168
1148
1169 @mock.patch.object(UserGroupModel, 'remove_user_from_group', crash)
1149 @mock.patch.object(UserGroupModel, 'remove_user_from_group', crash)
1170 def test_api_remove_user_from_users_group_exception_occurred(self):
1150 def test_api_remove_user_from_users_group_exception_occurred(self):
1171 gr_name = 'test_group_3'
1151 gr_name = 'test_group_3'
1172 gr = UserGroupModel().create(gr_name)
1152 gr = UserGroupModel().create(gr_name)
1173 UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
1153 UserGroupModel().add_user_to_group(gr, user=TEST_USER_ADMIN_LOGIN)
1174 Session().commit()
1154 Session().commit()
1175 id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
1155 id_, params = _build_data(self.apikey, 'remove_user_from_users_group',
1176 usersgroupid=gr_name,
1156 usersgroupid=gr_name,
1177 userid=TEST_USER_ADMIN_LOGIN)
1157 userid=TEST_USER_ADMIN_LOGIN)
1178 response = api_call(self, params)
1158 response = api_call(self, params)
1179
1159
1180 expected = 'failed to remove member from user group `%s`' % gr_name
1160 expected = 'failed to remove member from user group `%s`' % gr_name
1181 self._compare_error(id_, expected, given=response.body)
1161 self._compare_error(id_, expected, given=response.body)
1182
1162
1183 UserGroupModel().delete(users_group=gr_name)
1163 UserGroupModel().delete(users_group=gr_name)
1184 Session().commit()
1164 Session().commit()
1185
1165
1186 @parameterized.expand([('none', 'repository.none'),
1166 @parameterized.expand([('none', 'repository.none'),
1187 ('read', 'repository.read'),
1167 ('read', 'repository.read'),
1188 ('write', 'repository.write'),
1168 ('write', 'repository.write'),
1189 ('admin', 'repository.admin')])
1169 ('admin', 'repository.admin')])
1190 def test_api_grant_user_permission(self, name, perm):
1170 def test_api_grant_user_permission(self, name, perm):
1191 id_, params = _build_data(self.apikey, 'grant_user_permission',
1171 id_, params = _build_data(self.apikey, 'grant_user_permission',
1192 repoid=self.REPO,
1172 repoid=self.REPO,
1193 userid=TEST_USER_ADMIN_LOGIN,
1173 userid=TEST_USER_ADMIN_LOGIN,
1194 perm=perm)
1174 perm=perm)
1195 response = api_call(self, params)
1175 response = api_call(self, params)
1196
1176
1197 ret = {
1177 ret = {
1198 'msg': 'Granted perm: `%s` for user: `%s` in repo: `%s`' % (
1178 'msg': 'Granted perm: `%s` for user: `%s` in repo: `%s`' % (
1199 perm, TEST_USER_ADMIN_LOGIN, self.REPO
1179 perm, TEST_USER_ADMIN_LOGIN, self.REPO
1200 ),
1180 ),
1201 'success': True
1181 'success': True
1202 }
1182 }
1203 expected = ret
1183 expected = ret
1204 self._compare_ok(id_, expected, given=response.body)
1184 self._compare_ok(id_, expected, given=response.body)
1205
1185
1206 def test_api_grant_user_permission_wrong_permission(self):
1186 def test_api_grant_user_permission_wrong_permission(self):
1207 perm = 'haha.no.permission'
1187 perm = 'haha.no.permission'
1208 id_, params = _build_data(self.apikey, 'grant_user_permission',
1188 id_, params = _build_data(self.apikey, 'grant_user_permission',
1209 repoid=self.REPO,
1189 repoid=self.REPO,
1210 userid=TEST_USER_ADMIN_LOGIN,
1190 userid=TEST_USER_ADMIN_LOGIN,
1211 perm=perm)
1191 perm=perm)
1212 response = api_call(self, params)
1192 response = api_call(self, params)
1213
1193
1214 expected = 'permission `%s` does not exist' % perm
1194 expected = 'permission `%s` does not exist' % perm
1215 self._compare_error(id_, expected, given=response.body)
1195 self._compare_error(id_, expected, given=response.body)
1216
1196
1217 @mock.patch.object(RepoModel, 'grant_user_permission', crash)
1197 @mock.patch.object(RepoModel, 'grant_user_permission', crash)
1218 def test_api_grant_user_permission_exception_when_adding(self):
1198 def test_api_grant_user_permission_exception_when_adding(self):
1219 perm = 'repository.read'
1199 perm = 'repository.read'
1220 id_, params = _build_data(self.apikey, 'grant_user_permission',
1200 id_, params = _build_data(self.apikey, 'grant_user_permission',
1221 repoid=self.REPO,
1201 repoid=self.REPO,
1222 userid=TEST_USER_ADMIN_LOGIN,
1202 userid=TEST_USER_ADMIN_LOGIN,
1223 perm=perm)
1203 perm=perm)
1224 response = api_call(self, params)
1204 response = api_call(self, params)
1225
1205
1226 expected = 'failed to edit permission for user: `%s` in repo: `%s`' % (
1206 expected = 'failed to edit permission for user: `%s` in repo: `%s`' % (
1227 TEST_USER_ADMIN_LOGIN, self.REPO
1207 TEST_USER_ADMIN_LOGIN, self.REPO
1228 )
1208 )
1229 self._compare_error(id_, expected, given=response.body)
1209 self._compare_error(id_, expected, given=response.body)
1230
1210
1231 def test_api_revoke_user_permission(self):
1211 def test_api_revoke_user_permission(self):
1232 id_, params = _build_data(self.apikey, 'revoke_user_permission',
1212 id_, params = _build_data(self.apikey, 'revoke_user_permission',
1233 repoid=self.REPO,
1213 repoid=self.REPO,
1234 userid=TEST_USER_ADMIN_LOGIN,)
1214 userid=TEST_USER_ADMIN_LOGIN,)
1235 response = api_call(self, params)
1215 response = api_call(self, params)
1236
1216
1237 expected = {
1217 expected = {
1238 'msg': 'Revoked perm for user: `%s` in repo: `%s`' % (
1218 'msg': 'Revoked perm for user: `%s` in repo: `%s`' % (
1239 TEST_USER_ADMIN_LOGIN, self.REPO
1219 TEST_USER_ADMIN_LOGIN, self.REPO
1240 ),
1220 ),
1241 'success': True
1221 'success': True
1242 }
1222 }
1243 self._compare_ok(id_, expected, given=response.body)
1223 self._compare_ok(id_, expected, given=response.body)
1244
1224
1245 @mock.patch.object(RepoModel, 'revoke_user_permission', crash)
1225 @mock.patch.object(RepoModel, 'revoke_user_permission', crash)
1246 def test_api_revoke_user_permission_exception_when_adding(self):
1226 def test_api_revoke_user_permission_exception_when_adding(self):
1247 id_, params = _build_data(self.apikey, 'revoke_user_permission',
1227 id_, params = _build_data(self.apikey, 'revoke_user_permission',
1248 repoid=self.REPO,
1228 repoid=self.REPO,
1249 userid=TEST_USER_ADMIN_LOGIN,)
1229 userid=TEST_USER_ADMIN_LOGIN,)
1250 response = api_call(self, params)
1230 response = api_call(self, params)
1251
1231
1252 expected = 'failed to edit permission for user: `%s` in repo: `%s`' % (
1232 expected = 'failed to edit permission for user: `%s` in repo: `%s`' % (
1253 TEST_USER_ADMIN_LOGIN, self.REPO
1233 TEST_USER_ADMIN_LOGIN, self.REPO
1254 )
1234 )
1255 self._compare_error(id_, expected, given=response.body)
1235 self._compare_error(id_, expected, given=response.body)
1256
1236
1257 @parameterized.expand([('none', 'repository.none'),
1237 @parameterized.expand([('none', 'repository.none'),
1258 ('read', 'repository.read'),
1238 ('read', 'repository.read'),
1259 ('write', 'repository.write'),
1239 ('write', 'repository.write'),
1260 ('admin', 'repository.admin')])
1240 ('admin', 'repository.admin')])
1261 def test_api_grant_users_group_permission(self, name, perm):
1241 def test_api_grant_users_group_permission(self, name, perm):
1262 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1242 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1263 repoid=self.REPO,
1243 repoid=self.REPO,
1264 usersgroupid=TEST_USER_GROUP,
1244 usersgroupid=TEST_USER_GROUP,
1265 perm=perm)
1245 perm=perm)
1266 response = api_call(self, params)
1246 response = api_call(self, params)
1267
1247
1268 ret = {
1248 ret = {
1269 'msg': 'Granted perm: `%s` for user group: `%s` in repo: `%s`' % (
1249 'msg': 'Granted perm: `%s` for user group: `%s` in repo: `%s`' % (
1270 perm, TEST_USER_GROUP, self.REPO
1250 perm, TEST_USER_GROUP, self.REPO
1271 ),
1251 ),
1272 'success': True
1252 'success': True
1273 }
1253 }
1274 expected = ret
1254 expected = ret
1275 self._compare_ok(id_, expected, given=response.body)
1255 self._compare_ok(id_, expected, given=response.body)
1276
1256
1277 def test_api_grant_users_group_permission_wrong_permission(self):
1257 def test_api_grant_users_group_permission_wrong_permission(self):
1278 perm = 'haha.no.permission'
1258 perm = 'haha.no.permission'
1279 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1259 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1280 repoid=self.REPO,
1260 repoid=self.REPO,
1281 usersgroupid=TEST_USER_GROUP,
1261 usersgroupid=TEST_USER_GROUP,
1282 perm=perm)
1262 perm=perm)
1283 response = api_call(self, params)
1263 response = api_call(self, params)
1284
1264
1285 expected = 'permission `%s` does not exist' % perm
1265 expected = 'permission `%s` does not exist' % perm
1286 self._compare_error(id_, expected, given=response.body)
1266 self._compare_error(id_, expected, given=response.body)
1287
1267
1288 @mock.patch.object(RepoModel, 'grant_users_group_permission', crash)
1268 @mock.patch.object(RepoModel, 'grant_users_group_permission', crash)
1289 def test_api_grant_users_group_permission_exception_when_adding(self):
1269 def test_api_grant_users_group_permission_exception_when_adding(self):
1290 perm = 'repository.read'
1270 perm = 'repository.read'
1291 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1271 id_, params = _build_data(self.apikey, 'grant_users_group_permission',
1292 repoid=self.REPO,
1272 repoid=self.REPO,
1293 usersgroupid=TEST_USER_GROUP,
1273 usersgroupid=TEST_USER_GROUP,
1294 perm=perm)
1274 perm=perm)
1295 response = api_call(self, params)
1275 response = api_call(self, params)
1296
1276
1297 expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
1277 expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
1298 TEST_USER_GROUP, self.REPO
1278 TEST_USER_GROUP, self.REPO
1299 )
1279 )
1300 self._compare_error(id_, expected, given=response.body)
1280 self._compare_error(id_, expected, given=response.body)
1301
1281
1302 def test_api_revoke_users_group_permission(self):
1282 def test_api_revoke_users_group_permission(self):
1303 RepoModel().grant_users_group_permission(repo=self.REPO,
1283 RepoModel().grant_users_group_permission(repo=self.REPO,
1304 group_name=TEST_USER_GROUP,
1284 group_name=TEST_USER_GROUP,
1305 perm='repository.read')
1285 perm='repository.read')
1306 Session().commit()
1286 Session().commit()
1307 id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
1287 id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
1308 repoid=self.REPO,
1288 repoid=self.REPO,
1309 usersgroupid=TEST_USER_GROUP,)
1289 usersgroupid=TEST_USER_GROUP,)
1310 response = api_call(self, params)
1290 response = api_call(self, params)
1311
1291
1312 expected = {
1292 expected = {
1313 'msg': 'Revoked perm for user group: `%s` in repo: `%s`' % (
1293 'msg': 'Revoked perm for user group: `%s` in repo: `%s`' % (
1314 TEST_USER_GROUP, self.REPO
1294 TEST_USER_GROUP, self.REPO
1315 ),
1295 ),
1316 'success': True
1296 'success': True
1317 }
1297 }
1318 self._compare_ok(id_, expected, given=response.body)
1298 self._compare_ok(id_, expected, given=response.body)
1319
1299
1320 @mock.patch.object(RepoModel, 'revoke_users_group_permission', crash)
1300 @mock.patch.object(RepoModel, 'revoke_users_group_permission', crash)
1321 def test_api_revoke_users_group_permission_exception_when_adding(self):
1301 def test_api_revoke_users_group_permission_exception_when_adding(self):
1322
1302
1323 id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
1303 id_, params = _build_data(self.apikey, 'revoke_users_group_permission',
1324 repoid=self.REPO,
1304 repoid=self.REPO,
1325 usersgroupid=TEST_USER_GROUP,)
1305 usersgroupid=TEST_USER_GROUP,)
1326 response = api_call(self, params)
1306 response = api_call(self, params)
1327
1307
1328 expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
1308 expected = 'failed to edit permission for user group: `%s` in repo: `%s`' % (
1329 TEST_USER_GROUP, self.REPO
1309 TEST_USER_GROUP, self.REPO
1330 )
1310 )
1331 self._compare_error(id_, expected, given=response.body)
1311 self._compare_error(id_, expected, given=response.body)
@@ -1,43 +1,102 b''
1 """
1 """
2 Helpers for fixture generation
2 Helpers for fixture generation
3 """
3 """
4 import os
5 import unittest
6 from rhodecode.tests import *
4 from rhodecode.tests import *
7 from rhodecode.model.db import Repository, User
5 from rhodecode.model.db import Repository, User, RepoGroup
8 from rhodecode.model.meta import Session
6 from rhodecode.model.meta import Session
9 from rhodecode.model.repo import RepoModel
7 from rhodecode.model.repo import RepoModel
8 from rhodecode.model.repos_group import ReposGroupModel
10
9
11
10
12 class Fixture(object):
11 class Fixture(object):
13
12
14 def __init__(self):
13 def __init__(self):
15 pass
14 pass
16
15
16 def _get_repo_create_params(self, **custom):
17 defs = dict(
18 repo_name=None,
19 repo_type='hg',
20 clone_uri='',
21 repo_group='',
22 repo_description='DESC',
23 repo_private=False,
24 repo_landing_rev='tip'
25 )
26 defs.update(custom)
27 if 'repo_name_full' not in custom:
28 defs.update({'repo_name_full': defs['repo_name']})
29
30 return defs
31
32 def _get_group_create_params(self, **custom):
33 defs = dict(
34 group_name=None,
35 group_description='DESC',
36 group_parent_id=None,
37 perms_updates=[],
38 perms_new=[],
39 enable_locking=False,
40 recursive=False
41 )
42 defs.update(custom)
43
44 return defs
45
17 def create_repo(self, name, **kwargs):
46 def create_repo(self, name, **kwargs):
18 form_data = _get_repo_create_params(repo_name=name, **kwargs)
47 if 'skip_if_exists' in kwargs:
19 cur_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
48 del kwargs['skip_if_exists']
49 r = Repository.get_by_repo_name(name)
50 if r:
51 return r
52
53 if isinstance(kwargs.get('repos_group'), RepoGroup):
54 #TODO: rename the repos_group !
55 kwargs['repo_group'] = kwargs['repos_group'].group_id
56 del kwargs['repos_group']
57
58 form_data = self._get_repo_create_params(repo_name=name, **kwargs)
59 cur_user = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
20 RepoModel().create(form_data, cur_user)
60 RepoModel().create(form_data, cur_user)
61 Session().commit()
21 return Repository.get_by_repo_name(name)
62 return Repository.get_by_repo_name(name)
22
63
23 def create_fork(self, repo_to_fork, fork_name, **kwargs):
64 def create_fork(self, repo_to_fork, fork_name, **kwargs):
24 repo_to_fork = Repository.get_by_repo_name(repo_to_fork)
65 repo_to_fork = Repository.get_by_repo_name(repo_to_fork)
25 vcs_type = repo_to_fork.repo_type
66
67 form_data = self._get_repo_create_params(repo_name=fork_name,
68 fork_parent_id=repo_to_fork,
69 repo_type=repo_to_fork.repo_type,
70 **kwargs)
71 form_data['update_after_clone'] = False
72
73 #TODO: fix it !!
74 form_data['description'] = form_data['repo_description']
75 form_data['private'] = form_data['repo_private']
76 form_data['landing_rev'] = form_data['repo_landing_rev']
77
78 owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
79 RepoModel().create_fork(form_data, cur_user=owner)
80 Session().commit()
81 r = Repository.get_by_repo_name(fork_name)
82 assert r
83 return r
26
84
27 form_data = dict(
85 def destroy_repo(self, repo_name):
28 repo_name=fork_name,
86 RepoModel().delete(repo_name)
29 repo_name_full=fork_name,
87 Session().commit()
30 repo_group=None,
31 repo_type=vcs_type,
32 description='',
33 private=False,
34 copy_permissions=False,
35 landing_rev='tip',
36 update_after_clone=False,
37 fork_parent_id=repo_to_fork,
38 )
39 cur_user = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
40 RepoModel().create_fork(form_data, cur_user=cur_user)
41
88
89 def create_group(self, name, **kwargs):
90 if 'skip_if_exists' in kwargs:
91 del kwargs['skip_if_exists']
92 gr = RepoGroup.get_by_group_name(group_name=name)
93 if gr:
94 return gr
95 form_data = self._get_group_create_params(group_name=name, **kwargs)
96 owner = kwargs.get('cur_user', TEST_USER_ADMIN_LOGIN)
97 gr = ReposGroupModel().create(group_name=form_data['group_name'],
98 group_description=form_data['group_name'],
99 owner=owner, parent=form_data['group_parent_id'])
42 Session().commit()
100 Session().commit()
43 return Repository.get_by_repo_name(fork_name)
101 gr = RepoGroup.get_by_group_name(gr.group_name)
102 return gr
@@ -1,368 +1,371 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 import os
3 import os
4 import urllib
4 import urllib
5
5
6 from rhodecode.lib import vcs
6 from rhodecode.lib import vcs
7 from rhodecode.model.db import Repository, RepoGroup, UserRepoToPerm, User,\
7 from rhodecode.model.db import Repository, RepoGroup, UserRepoToPerm, User,\
8 Permission
8 Permission
9 from rhodecode.tests import *
9 from rhodecode.tests import *
10 from rhodecode.model.repos_group import ReposGroupModel
10 from rhodecode.model.repos_group import ReposGroupModel
11 from rhodecode.model.repo import RepoModel
11 from rhodecode.model.repo import RepoModel
12 from rhodecode.model.meta import Session
12 from rhodecode.model.meta import Session
13 from rhodecode.tests.fixture import Fixture
14
15 fixture = Fixture()
13
16
14
17
15 def _get_permission_for_user(user, repo):
18 def _get_permission_for_user(user, repo):
16 perm = UserRepoToPerm.query()\
19 perm = UserRepoToPerm.query()\
17 .filter(UserRepoToPerm.repository ==
20 .filter(UserRepoToPerm.repository ==
18 Repository.get_by_repo_name(repo))\
21 Repository.get_by_repo_name(repo))\
19 .filter(UserRepoToPerm.user == User.get_by_username(user))\
22 .filter(UserRepoToPerm.user == User.get_by_username(user))\
20 .all()
23 .all()
21 return perm
24 return perm
22
25
23
26
24 class TestAdminReposController(TestController):
27 class TestAdminReposController(TestController):
25
28
26 def test_index(self):
29 def test_index(self):
27 self.log_user()
30 self.log_user()
28 response = self.app.get(url('repos'))
31 response = self.app.get(url('repos'))
29 # Test response...
32 # Test response...
30
33
31 def test_index_as_xml(self):
34 def test_index_as_xml(self):
32 response = self.app.get(url('formatted_repos', format='xml'))
35 response = self.app.get(url('formatted_repos', format='xml'))
33
36
34 def test_create_hg(self):
37 def test_create_hg(self):
35 self.log_user()
38 self.log_user()
36 repo_name = NEW_HG_REPO
39 repo_name = NEW_HG_REPO
37 description = 'description for newly created repo'
40 description = 'description for newly created repo'
38 response = self.app.post(url('repos'),
41 response = self.app.post(url('repos'),
39 _get_repo_create_params(repo_private=False,
42 fixture._get_repo_create_params(repo_private=False,
40 repo_name=repo_name,
43 repo_name=repo_name,
41 repo_description=description))
44 repo_description=description))
42 self.checkSessionFlash(response,
45 self.checkSessionFlash(response,
43 'Created repository <a href="/%s">%s</a>'
46 'Created repository <a href="/%s">%s</a>'
44 % (repo_name, repo_name))
47 % (repo_name, repo_name))
45
48
46 #test if the repo was created in the database
49 #test if the repo was created in the database
47 new_repo = self.Session().query(Repository)\
50 new_repo = self.Session().query(Repository)\
48 .filter(Repository.repo_name == repo_name).one()
51 .filter(Repository.repo_name == repo_name).one()
49
52
50 self.assertEqual(new_repo.repo_name, repo_name)
53 self.assertEqual(new_repo.repo_name, repo_name)
51 self.assertEqual(new_repo.description, description)
54 self.assertEqual(new_repo.description, description)
52
55
53 #test if repository is visible in the list ?
56 #test if repository is visible in the list ?
54 response = response.follow()
57 response = response.follow()
55
58
56 response.mustcontain(repo_name)
59 response.mustcontain(repo_name)
57
60
58 #test if repository was created on filesystem
61 #test if repository was created on filesystem
59 try:
62 try:
60 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
63 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
61 except Exception:
64 except Exception:
62 self.fail('no repo %s in filesystem' % repo_name)
65 self.fail('no repo %s in filesystem' % repo_name)
63
66
64 def test_create_hg_non_ascii(self):
67 def test_create_hg_non_ascii(self):
65 self.log_user()
68 self.log_user()
66 non_ascii = "Δ…Δ™Ε‚"
69 non_ascii = "Δ…Δ™Ε‚"
67 repo_name = "%s%s" % (NEW_HG_REPO, non_ascii)
70 repo_name = "%s%s" % (NEW_HG_REPO, non_ascii)
68 repo_name_unicode = repo_name.decode('utf8')
71 repo_name_unicode = repo_name.decode('utf8')
69 description = 'description for newly created repo' + non_ascii
72 description = 'description for newly created repo' + non_ascii
70 description_unicode = description.decode('utf8')
73 description_unicode = description.decode('utf8')
71 private = False
74 private = False
72 response = self.app.post(url('repos'),
75 response = self.app.post(url('repos'),
73 _get_repo_create_params(repo_private=False,
76 fixture._get_repo_create_params(repo_private=False,
74 repo_name=repo_name,
77 repo_name=repo_name,
75 repo_description=description))
78 repo_description=description))
76 self.checkSessionFlash(response,
79 self.checkSessionFlash(response,
77 u'Created repository <a href="/%s">%s</a>'
80 u'Created repository <a href="/%s">%s</a>'
78 % (urllib.quote(repo_name), repo_name_unicode))
81 % (urllib.quote(repo_name), repo_name_unicode))
79 #test if the repo was created in the database
82 #test if the repo was created in the database
80 new_repo = self.Session().query(Repository)\
83 new_repo = self.Session().query(Repository)\
81 .filter(Repository.repo_name == repo_name_unicode).one()
84 .filter(Repository.repo_name == repo_name_unicode).one()
82
85
83 self.assertEqual(new_repo.repo_name, repo_name_unicode)
86 self.assertEqual(new_repo.repo_name, repo_name_unicode)
84 self.assertEqual(new_repo.description, description_unicode)
87 self.assertEqual(new_repo.description, description_unicode)
85
88
86 #test if repository is visible in the list ?
89 #test if repository is visible in the list ?
87 response = response.follow()
90 response = response.follow()
88
91
89 response.mustcontain(repo_name)
92 response.mustcontain(repo_name)
90
93
91 #test if repository was created on filesystem
94 #test if repository was created on filesystem
92 try:
95 try:
93 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
96 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
94 except Exception:
97 except Exception:
95 self.fail('no repo %s in filesystem' % repo_name)
98 self.fail('no repo %s in filesystem' % repo_name)
96
99
97 def test_create_hg_in_group(self):
100 def test_create_hg_in_group(self):
98 self.log_user()
101 self.log_user()
99
102
100 ## create GROUP
103 ## create GROUP
101 group_name = 'sometest'
104 group_name = 'sometest'
102 gr = ReposGroupModel().create(group_name=group_name,
105 gr = ReposGroupModel().create(group_name=group_name,
103 group_description='test',
106 group_description='test',
104 owner=TEST_USER_ADMIN_LOGIN)
107 owner=TEST_USER_ADMIN_LOGIN)
105 self.Session().commit()
108 self.Session().commit()
106
109
107 repo_name = 'ingroup'
110 repo_name = 'ingroup'
108 repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
111 repo_name_full = RepoGroup.url_sep().join([group_name, repo_name])
109 description = 'description for newly created repo'
112 description = 'description for newly created repo'
110 response = self.app.post(url('repos'),
113 response = self.app.post(url('repos'),
111 _get_repo_create_params(repo_private=False,
114 fixture._get_repo_create_params(repo_private=False,
112 repo_name=repo_name,
115 repo_name=repo_name,
113 repo_description=description,
116 repo_description=description,
114 repo_group=gr.group_id,))
117 repo_group=gr.group_id,))
115
118
116 self.checkSessionFlash(response,
119 self.checkSessionFlash(response,
117 'Created repository <a href="/%s">%s</a>'
120 'Created repository <a href="/%s">%s</a>'
118 % (repo_name, repo_name))
121 % (repo_name, repo_name))
119 #test if the repo was created in the database
122 #test if the repo was created in the database
120 new_repo = self.Session().query(Repository)\
123 new_repo = self.Session().query(Repository)\
121 .filter(Repository.repo_name == repo_name_full).one()
124 .filter(Repository.repo_name == repo_name_full).one()
122
125
123 self.assertEqual(new_repo.repo_name, repo_name_full)
126 self.assertEqual(new_repo.repo_name, repo_name_full)
124 self.assertEqual(new_repo.description, description)
127 self.assertEqual(new_repo.description, description)
125
128
126 #test if repository is visible in the list ?
129 #test if repository is visible in the list ?
127 response = response.follow()
130 response = response.follow()
128
131
129 response.mustcontain(repo_name_full)
132 response.mustcontain(repo_name_full)
130
133
131 #test if repository was created on filesystem
134 #test if repository was created on filesystem
132 try:
135 try:
133 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
136 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name_full))
134 except Exception:
137 except Exception:
135 ReposGroupModel().delete(group_name)
138 ReposGroupModel().delete(group_name)
136 self.Session().commit()
139 self.Session().commit()
137 self.fail('no repo %s in filesystem' % repo_name)
140 self.fail('no repo %s in filesystem' % repo_name)
138
141
139 RepoModel().delete(repo_name_full)
142 RepoModel().delete(repo_name_full)
140 ReposGroupModel().delete(group_name)
143 ReposGroupModel().delete(group_name)
141 self.Session().commit()
144 self.Session().commit()
142
145
143 def test_create_git(self):
146 def test_create_git(self):
144 self.log_user()
147 self.log_user()
145 repo_name = NEW_GIT_REPO
148 repo_name = NEW_GIT_REPO
146 description = 'description for newly created repo'
149 description = 'description for newly created repo'
147
150
148 response = self.app.post(url('repos'),
151 response = self.app.post(url('repos'),
149 _get_repo_create_params(repo_private=False,
152 fixture._get_repo_create_params(repo_private=False,
150 repo_type='git',
153 repo_type='git',
151 repo_name=repo_name,
154 repo_name=repo_name,
152 repo_description=description))
155 repo_description=description))
153 self.checkSessionFlash(response,
156 self.checkSessionFlash(response,
154 'Created repository <a href="/%s">%s</a>'
157 'Created repository <a href="/%s">%s</a>'
155 % (repo_name, repo_name))
158 % (repo_name, repo_name))
156
159
157 #test if the repo was created in the database
160 #test if the repo was created in the database
158 new_repo = self.Session().query(Repository)\
161 new_repo = self.Session().query(Repository)\
159 .filter(Repository.repo_name == repo_name).one()
162 .filter(Repository.repo_name == repo_name).one()
160
163
161 self.assertEqual(new_repo.repo_name, repo_name)
164 self.assertEqual(new_repo.repo_name, repo_name)
162 self.assertEqual(new_repo.description, description)
165 self.assertEqual(new_repo.description, description)
163
166
164 #test if repository is visible in the list ?
167 #test if repository is visible in the list ?
165 response = response.follow()
168 response = response.follow()
166
169
167 response.mustcontain(repo_name)
170 response.mustcontain(repo_name)
168
171
169 #test if repository was created on filesystem
172 #test if repository was created on filesystem
170 try:
173 try:
171 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
174 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
172 except Exception:
175 except Exception:
173 self.fail('no repo %s in filesystem' % repo_name)
176 self.fail('no repo %s in filesystem' % repo_name)
174
177
175 def test_create_git_non_ascii(self):
178 def test_create_git_non_ascii(self):
176 self.log_user()
179 self.log_user()
177 non_ascii = "Δ…Δ™Ε‚"
180 non_ascii = "Δ…Δ™Ε‚"
178 repo_name = "%s%s" % (NEW_GIT_REPO, non_ascii)
181 repo_name = "%s%s" % (NEW_GIT_REPO, non_ascii)
179 repo_name_unicode = repo_name.decode('utf8')
182 repo_name_unicode = repo_name.decode('utf8')
180 description = 'description for newly created repo' + non_ascii
183 description = 'description for newly created repo' + non_ascii
181 description_unicode = description.decode('utf8')
184 description_unicode = description.decode('utf8')
182 private = False
185 private = False
183 response = self.app.post(url('repos'),
186 response = self.app.post(url('repos'),
184 _get_repo_create_params(repo_private=False,
187 fixture._get_repo_create_params(repo_private=False,
185 repo_type='git',
188 repo_type='git',
186 repo_name=repo_name,
189 repo_name=repo_name,
187 repo_description=description))
190 repo_description=description))
188
191
189 self.checkSessionFlash(response,
192 self.checkSessionFlash(response,
190 u'Created repository <a href="/%s">%s</a>'
193 u'Created repository <a href="/%s">%s</a>'
191 % (urllib.quote(repo_name), repo_name_unicode))
194 % (urllib.quote(repo_name), repo_name_unicode))
192
195
193 #test if the repo was created in the database
196 #test if the repo was created in the database
194 new_repo = self.Session().query(Repository)\
197 new_repo = self.Session().query(Repository)\
195 .filter(Repository.repo_name == repo_name_unicode).one()
198 .filter(Repository.repo_name == repo_name_unicode).one()
196
199
197 self.assertEqual(new_repo.repo_name, repo_name_unicode)
200 self.assertEqual(new_repo.repo_name, repo_name_unicode)
198 self.assertEqual(new_repo.description, description_unicode)
201 self.assertEqual(new_repo.description, description_unicode)
199
202
200 #test if repository is visible in the list ?
203 #test if repository is visible in the list ?
201 response = response.follow()
204 response = response.follow()
202
205
203 response.mustcontain(repo_name)
206 response.mustcontain(repo_name)
204
207
205 #test if repository was created on filesystem
208 #test if repository was created on filesystem
206 try:
209 try:
207 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
210 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
208 except Exception:
211 except Exception:
209 self.fail('no repo %s in filesystem' % repo_name)
212 self.fail('no repo %s in filesystem' % repo_name)
210
213
211 def test_update(self):
214 def test_update(self):
212 response = self.app.put(url('repo', repo_name=HG_REPO))
215 response = self.app.put(url('repo', repo_name=HG_REPO))
213
216
214 def test_update_browser_fakeout(self):
217 def test_update_browser_fakeout(self):
215 response = self.app.post(url('repo', repo_name=HG_REPO),
218 response = self.app.post(url('repo', repo_name=HG_REPO),
216 params=dict(_method='put'))
219 params=dict(_method='put'))
217
220
218 def test_delete_hg(self):
221 def test_delete_hg(self):
219 self.log_user()
222 self.log_user()
220 repo_name = 'vcs_test_new_to_delete'
223 repo_name = 'vcs_test_new_to_delete'
221 description = 'description for newly created repo'
224 description = 'description for newly created repo'
222 response = self.app.post(url('repos'),
225 response = self.app.post(url('repos'),
223 _get_repo_create_params(repo_private=False,
226 fixture._get_repo_create_params(repo_private=False,
224 repo_type='hg',
227 repo_type='hg',
225 repo_name=repo_name,
228 repo_name=repo_name,
226 repo_description=description))
229 repo_description=description))
227
230
228 self.checkSessionFlash(response,
231 self.checkSessionFlash(response,
229 'Created repository <a href="/%s">%s</a>'
232 'Created repository <a href="/%s">%s</a>'
230 % (repo_name, repo_name))
233 % (repo_name, repo_name))
231 #test if the repo was created in the database
234 #test if the repo was created in the database
232 new_repo = self.Session().query(Repository)\
235 new_repo = self.Session().query(Repository)\
233 .filter(Repository.repo_name == repo_name).one()
236 .filter(Repository.repo_name == repo_name).one()
234
237
235 self.assertEqual(new_repo.repo_name, repo_name)
238 self.assertEqual(new_repo.repo_name, repo_name)
236 self.assertEqual(new_repo.description, description)
239 self.assertEqual(new_repo.description, description)
237
240
238 #test if repository is visible in the list ?
241 #test if repository is visible in the list ?
239 response = response.follow()
242 response = response.follow()
240
243
241 response.mustcontain(repo_name)
244 response.mustcontain(repo_name)
242
245
243 #test if repository was created on filesystem
246 #test if repository was created on filesystem
244 try:
247 try:
245 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
248 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
246 except Exception:
249 except Exception:
247 self.fail('no repo %s in filesystem' % repo_name)
250 self.fail('no repo %s in filesystem' % repo_name)
248
251
249 response = self.app.delete(url('repo', repo_name=repo_name))
252 response = self.app.delete(url('repo', repo_name=repo_name))
250
253
251 self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name))
254 self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name))
252
255
253 response.follow()
256 response.follow()
254
257
255 #check if repo was deleted from db
258 #check if repo was deleted from db
256 deleted_repo = self.Session().query(Repository)\
259 deleted_repo = self.Session().query(Repository)\
257 .filter(Repository.repo_name == repo_name).scalar()
260 .filter(Repository.repo_name == repo_name).scalar()
258
261
259 self.assertEqual(deleted_repo, None)
262 self.assertEqual(deleted_repo, None)
260
263
261 self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
264 self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
262 False)
265 False)
263
266
264 def test_delete_git(self):
267 def test_delete_git(self):
265 self.log_user()
268 self.log_user()
266 repo_name = 'vcs_test_new_to_delete'
269 repo_name = 'vcs_test_new_to_delete'
267 description = 'description for newly created repo'
270 description = 'description for newly created repo'
268 private = False
271 private = False
269 response = self.app.post(url('repos'),
272 response = self.app.post(url('repos'),
270 _get_repo_create_params(repo_private=False,
273 fixture._get_repo_create_params(repo_private=False,
271 repo_type='git',
274 repo_type='git',
272 repo_name=repo_name,
275 repo_name=repo_name,
273 repo_description=description))
276 repo_description=description))
274
277
275 self.checkSessionFlash(response,
278 self.checkSessionFlash(response,
276 'Created repository <a href="/%s">%s</a>'
279 'Created repository <a href="/%s">%s</a>'
277 % (repo_name, repo_name))
280 % (repo_name, repo_name))
278 #test if the repo was created in the database
281 #test if the repo was created in the database
279 new_repo = self.Session().query(Repository)\
282 new_repo = self.Session().query(Repository)\
280 .filter(Repository.repo_name == repo_name).one()
283 .filter(Repository.repo_name == repo_name).one()
281
284
282 self.assertEqual(new_repo.repo_name, repo_name)
285 self.assertEqual(new_repo.repo_name, repo_name)
283 self.assertEqual(new_repo.description, description)
286 self.assertEqual(new_repo.description, description)
284
287
285 #test if repository is visible in the list ?
288 #test if repository is visible in the list ?
286 response = response.follow()
289 response = response.follow()
287
290
288 response.mustcontain(repo_name)
291 response.mustcontain(repo_name)
289
292
290 #test if repository was created on filesystem
293 #test if repository was created on filesystem
291 try:
294 try:
292 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
295 vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
293 except Exception:
296 except Exception:
294 self.fail('no repo %s in filesystem' % repo_name)
297 self.fail('no repo %s in filesystem' % repo_name)
295
298
296 response = self.app.delete(url('repo', repo_name=repo_name))
299 response = self.app.delete(url('repo', repo_name=repo_name))
297
300
298 self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name))
301 self.checkSessionFlash(response, 'Deleted repository %s' % (repo_name))
299
302
300 response.follow()
303 response.follow()
301
304
302 #check if repo was deleted from db
305 #check if repo was deleted from db
303 deleted_repo = self.Session().query(Repository)\
306 deleted_repo = self.Session().query(Repository)\
304 .filter(Repository.repo_name == repo_name).scalar()
307 .filter(Repository.repo_name == repo_name).scalar()
305
308
306 self.assertEqual(deleted_repo, None)
309 self.assertEqual(deleted_repo, None)
307
310
308 self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
311 self.assertEqual(os.path.isdir(os.path.join(TESTS_TMP_PATH, repo_name)),
309 False)
312 False)
310
313
311 def test_delete_repo_with_group(self):
314 def test_delete_repo_with_group(self):
312 #TODO:
315 #TODO:
313 pass
316 pass
314
317
315 def test_delete_browser_fakeout(self):
318 def test_delete_browser_fakeout(self):
316 response = self.app.post(url('repo', repo_name=HG_REPO),
319 response = self.app.post(url('repo', repo_name=HG_REPO),
317 params=dict(_method='delete'))
320 params=dict(_method='delete'))
318
321
319 def test_show_hg(self):
322 def test_show_hg(self):
320 self.log_user()
323 self.log_user()
321 response = self.app.get(url('repo', repo_name=HG_REPO))
324 response = self.app.get(url('repo', repo_name=HG_REPO))
322
325
323 def test_show_git(self):
326 def test_show_git(self):
324 self.log_user()
327 self.log_user()
325 response = self.app.get(url('repo', repo_name=GIT_REPO))
328 response = self.app.get(url('repo', repo_name=GIT_REPO))
326
329
327
330
328 def test_edit(self):
331 def test_edit(self):
329 response = self.app.get(url('edit_repo', repo_name=HG_REPO))
332 response = self.app.get(url('edit_repo', repo_name=HG_REPO))
330
333
331 def test_set_private_flag_sets_default_to_none(self):
334 def test_set_private_flag_sets_default_to_none(self):
332 self.log_user()
335 self.log_user()
333 #initially repository perm should be read
336 #initially repository perm should be read
334 perm = _get_permission_for_user(user='default', repo=HG_REPO)
337 perm = _get_permission_for_user(user='default', repo=HG_REPO)
335 self.assertTrue(len(perm), 1)
338 self.assertTrue(len(perm), 1)
336 self.assertEqual(perm[0].permission.permission_name, 'repository.read')
339 self.assertEqual(perm[0].permission.permission_name, 'repository.read')
337 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False)
340 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False)
338
341
339 response = self.app.put(url('repo', repo_name=HG_REPO),
342 response = self.app.put(url('repo', repo_name=HG_REPO),
340 _get_repo_create_params(repo_private=1,
343 fixture._get_repo_create_params(repo_private=1,
341 repo_name=HG_REPO,
344 repo_name=HG_REPO,
342 user=TEST_USER_ADMIN_LOGIN))
345 user=TEST_USER_ADMIN_LOGIN))
343 self.checkSessionFlash(response,
346 self.checkSessionFlash(response,
344 msg='Repository %s updated successfully' % (HG_REPO))
347 msg='Repository %s updated successfully' % (HG_REPO))
345 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, True)
348 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, True)
346
349
347 #now the repo default permission should be None
350 #now the repo default permission should be None
348 perm = _get_permission_for_user(user='default', repo=HG_REPO)
351 perm = _get_permission_for_user(user='default', repo=HG_REPO)
349 self.assertTrue(len(perm), 1)
352 self.assertTrue(len(perm), 1)
350 self.assertEqual(perm[0].permission.permission_name, 'repository.none')
353 self.assertEqual(perm[0].permission.permission_name, 'repository.none')
351
354
352 response = self.app.put(url('repo', repo_name=HG_REPO),
355 response = self.app.put(url('repo', repo_name=HG_REPO),
353 _get_repo_create_params(repo_private=False,
356 fixture._get_repo_create_params(repo_private=False,
354 repo_name=HG_REPO,
357 repo_name=HG_REPO,
355 user=TEST_USER_ADMIN_LOGIN))
358 user=TEST_USER_ADMIN_LOGIN))
356 self.checkSessionFlash(response,
359 self.checkSessionFlash(response,
357 msg='Repository %s updated successfully' % (HG_REPO))
360 msg='Repository %s updated successfully' % (HG_REPO))
358 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False)
361 self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False)
359
362
360 #we turn off private now the repo default permission should stay None
363 #we turn off private now the repo default permission should stay None
361 perm = _get_permission_for_user(user='default', repo=HG_REPO)
364 perm = _get_permission_for_user(user='default', repo=HG_REPO)
362 self.assertTrue(len(perm), 1)
365 self.assertTrue(len(perm), 1)
363 self.assertEqual(perm[0].permission.permission_name, 'repository.none')
366 self.assertEqual(perm[0].permission.permission_name, 'repository.none')
364
367
365 #update this permission back
368 #update this permission back
366 perm[0].permission = Permission.get_by_key('repository.read')
369 perm[0].permission = Permission.get_by_key('repository.read')
367 Session().add(perm[0])
370 Session().add(perm[0])
368 Session().commit()
371 Session().commit()
@@ -1,417 +1,411 b''
1 from rhodecode.tests import *
1 from rhodecode.tests import *
2 from rhodecode.model.repo import RepoModel
2 from rhodecode.model.repo import RepoModel
3 from rhodecode.model.meta import Session
3 from rhodecode.model.meta import Session
4 from rhodecode.model.db import Repository
4 from rhodecode.model.db import Repository
5 from rhodecode.model.scm import ScmModel
5 from rhodecode.model.scm import ScmModel
6 from rhodecode.lib.vcs.backends.base import EmptyChangeset
6 from rhodecode.lib.vcs.backends.base import EmptyChangeset
7 from rhodecode.tests.fixture import Fixture
7 from rhodecode.tests.fixture import Fixture
8
8
9 fixture = Fixture()
9 fixture = Fixture()
10
10
11
11
12 def _commit_change(repo, filename, content, message, vcs_type, parent=None, newfile=False):
12 def _commit_change(repo, filename, content, message, vcs_type, parent=None, newfile=False):
13 repo = Repository.get_by_repo_name(repo)
13 repo = Repository.get_by_repo_name(repo)
14 _cs = parent
14 _cs = parent
15 if not parent:
15 if not parent:
16 _cs = EmptyChangeset(alias=vcs_type)
16 _cs = EmptyChangeset(alias=vcs_type)
17
17
18 if newfile:
18 if newfile:
19 cs = ScmModel().create_node(
19 cs = ScmModel().create_node(
20 repo=repo.scm_instance, repo_name=repo.repo_name,
20 repo=repo.scm_instance, repo_name=repo.repo_name,
21 cs=_cs, user=TEST_USER_ADMIN_LOGIN,
21 cs=_cs, user=TEST_USER_ADMIN_LOGIN,
22 author=TEST_USER_ADMIN_LOGIN,
22 author=TEST_USER_ADMIN_LOGIN,
23 message=message,
23 message=message,
24 content=content,
24 content=content,
25 f_path=filename
25 f_path=filename
26 )
26 )
27 else:
27 else:
28 cs = ScmModel().commit_change(
28 cs = ScmModel().commit_change(
29 repo=repo.scm_instance, repo_name=repo.repo_name,
29 repo=repo.scm_instance, repo_name=repo.repo_name,
30 cs=parent, user=TEST_USER_ADMIN_LOGIN,
30 cs=parent, user=TEST_USER_ADMIN_LOGIN,
31 author=TEST_USER_ADMIN_LOGIN,
31 author=TEST_USER_ADMIN_LOGIN,
32 message=message,
32 message=message,
33 content=content,
33 content=content,
34 f_path=filename
34 f_path=filename
35 )
35 )
36 return cs
36 return cs
37
37
38
38
39 class TestCompareController(TestController):
39 class TestCompareController(TestController):
40
40
41 def setUp(self):
41 def setUp(self):
42 self.r1_id = None
42 self.r1_id = None
43 self.r2_id = None
43 self.r2_id = None
44
44
45 def tearDown(self):
45 def tearDown(self):
46 if self.r2_id:
46 if self.r2_id:
47 RepoModel().delete(self.r2_id)
47 RepoModel().delete(self.r2_id)
48 if self.r1_id:
48 if self.r1_id:
49 RepoModel().delete(self.r1_id)
49 RepoModel().delete(self.r1_id)
50 Session().commit()
50 Session().commit()
51 Session.remove()
51 Session.remove()
52
52
53 def test_compare_forks_on_branch_extra_commits_hg(self):
53 def test_compare_forks_on_branch_extra_commits_hg(self):
54 self.log_user()
54 self.log_user()
55 repo1 = RepoModel().create_repo(repo_name='one', repo_type='hg',
55 repo1 = fixture.create_repo('one', repo_type='hg',
56 description='diff-test',
56 repo_description='diff-test',
57 owner=TEST_USER_ADMIN_LOGIN)
57 cur_user=TEST_USER_ADMIN_LOGIN)
58 Session().commit()
59 self.r1_id = repo1.repo_id
58 self.r1_id = repo1.repo_id
60 #commit something !
59 #commit something !
61 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
60 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
62 message='commit1', vcs_type='hg', parent=None, newfile=True)
61 message='commit1', vcs_type='hg', parent=None, newfile=True)
63
62
64 #fork this repo
63 #fork this repo
65 repo2 = fixture.create_fork('one', 'one-fork')
64 repo2 = fixture.create_fork('one', 'one-fork')
66 self.r2_id = repo2.repo_id
65 self.r2_id = repo2.repo_id
67
66
68 #add two extra commit into fork
67 #add two extra commit into fork
69 cs1 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\n',
68 cs1 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\n',
70 message='commit2', vcs_type='hg', parent=cs0)
69 message='commit2', vcs_type='hg', parent=cs0)
71
70
72 cs2 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\nline3\n',
71 cs2 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\nline3\n',
73 message='commit3', vcs_type='hg', parent=cs1)
72 message='commit3', vcs_type='hg', parent=cs1)
74
73
75 rev1 = 'default'
74 rev1 = 'default'
76 rev2 = 'default'
75 rev2 = 'default'
77
76
78 response = self.app.get(url(controller='compare', action='index',
77 response = self.app.get(url(controller='compare', action='index',
79 repo_name=repo1.repo_name,
78 repo_name=repo1.repo_name,
80 org_ref_type="branch",
79 org_ref_type="branch",
81 org_ref=rev2,
80 org_ref=rev2,
82 other_repo=repo2.repo_name,
81 other_repo=repo2.repo_name,
83 other_ref_type="branch",
82 other_ref_type="branch",
84 other_ref=rev1,
83 other_ref=rev1,
85 merge='1',
84 merge='1',
86 ))
85 ))
87
86
88 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
87 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
89 response.mustcontain("""Showing 2 commits""")
88 response.mustcontain("""Showing 2 commits""")
90 response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
89 response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
91
90
92 response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
91 response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
93 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
92 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
94
93
95 response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
94 response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
96 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
95 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
97 ## files
96 ## files
98 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=1#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
97 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=1#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
99 #swap
98 #swap
100 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
99 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
101
100
102 def test_compare_forks_on_branch_extra_commits_origin_has_incomming_hg(self):
101 def test_compare_forks_on_branch_extra_commits_origin_has_incomming_hg(self):
103 self.log_user()
102 self.log_user()
104
103
105 repo1 = RepoModel().create_repo(repo_name='one', repo_type='hg',
104 repo1 = fixture.create_repo('one', repo_type='hg',
106 description='diff-test',
105 repo_description='diff-test',
107 owner=TEST_USER_ADMIN_LOGIN)
106 cur_user=TEST_USER_ADMIN_LOGIN)
108 Session().commit()
107
109 self.r1_id = repo1.repo_id
108 self.r1_id = repo1.repo_id
110
109
111 #commit something !
110 #commit something !
112 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
111 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
113 message='commit1', vcs_type='hg', parent=None, newfile=True)
112 message='commit1', vcs_type='hg', parent=None, newfile=True)
114
113
115 #fork this repo
114 #fork this repo
116 repo2 = fixture.create_fork('one', 'one-fork')
115 repo2 = fixture.create_fork('one', 'one-fork')
117 self.r2_id = repo2.repo_id
116 self.r2_id = repo2.repo_id
118
117
119 #now commit something to origin repo
118 #now commit something to origin repo
120 cs1_prim = _commit_change(repo1.repo_name, filename='file2', content='line1file2\n',
119 cs1_prim = _commit_change(repo1.repo_name, filename='file2', content='line1file2\n',
121 message='commit2', vcs_type='hg', parent=cs0, newfile=True)
120 message='commit2', vcs_type='hg', parent=cs0, newfile=True)
122
121
123 #add two extra commit into fork
122 #add two extra commit into fork
124 cs1 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\n',
123 cs1 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\n',
125 message='commit2', vcs_type='hg', parent=cs0)
124 message='commit2', vcs_type='hg', parent=cs0)
126
125
127 cs2 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\nline3\n',
126 cs2 = _commit_change(repo2.repo_name, filename='file1', content='line1\nline2\nline3\n',
128 message='commit3', vcs_type='hg', parent=cs1)
127 message='commit3', vcs_type='hg', parent=cs1)
129
128
130 rev1 = 'default'
129 rev1 = 'default'
131 rev2 = 'default'
130 rev2 = 'default'
132
131
133 response = self.app.get(url(controller='compare', action='index',
132 response = self.app.get(url(controller='compare', action='index',
134 repo_name=repo1.repo_name,
133 repo_name=repo1.repo_name,
135 org_ref_type="branch",
134 org_ref_type="branch",
136 org_ref=rev2,
135 org_ref=rev2,
137 other_repo=repo2.repo_name,
136 other_repo=repo2.repo_name,
138 other_ref_type="branch",
137 other_ref_type="branch",
139 other_ref=rev1,
138 other_ref=rev1,
140 merge='x',
139 merge='x',
141 ))
140 ))
142 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
141 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, rev2, repo2.repo_name, rev1))
143 response.mustcontain("""Showing 2 commits""")
142 response.mustcontain("""Showing 2 commits""")
144 response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
143 response.mustcontain("""1 file changed with 2 insertions and 0 deletions""")
145
144
146 response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
145 response.mustcontain("""<div class="message tooltip" title="commit2" style="white-space:normal">commit2</div>""")
147 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
146 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
148
147
149 response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
148 response.mustcontain("""<a href="/%s/changeset/%s">r1:%s</a>""" % (repo2.repo_name, cs1.raw_id, cs1.short_id))
150 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
149 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo2.repo_name, cs2.raw_id, cs2.short_id))
151 ## files
150 ## files
152 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=x#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
151 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=x#C--826e8142e6ba">file1</a>""" % (repo1.repo_name, rev2, rev1, repo2.repo_name))
153 #swap
152 #swap
154 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
153 response.mustcontain("""<a href="/%s/compare/branch@%s...branch@%s?other_repo=%s&amp;merge=True">[swap]</a>""" % (repo2.repo_name, rev1, rev2, repo1.repo_name))
155
154
156 def test_compare_cherry_pick_changesets_from_bottom(self):
155 def test_compare_cherry_pick_changesets_from_bottom(self):
157
156
158 # repo1:
157 # repo1:
159 # cs0:
158 # cs0:
160 # cs1:
159 # cs1:
161 # repo1-fork- in which we will cherry pick bottom changesets
160 # repo1-fork- in which we will cherry pick bottom changesets
162 # cs0:
161 # cs0:
163 # cs1:
162 # cs1:
164 # cs2: x
163 # cs2: x
165 # cs3: x
164 # cs3: x
166 # cs4: x
165 # cs4: x
167 # cs5:
166 # cs5:
168 #make repo1, and cs1+cs2
167 #make repo1, and cs1+cs2
169 self.log_user()
168 self.log_user()
170
169
171 repo1 = RepoModel().create_repo(repo_name='repo1', repo_type='hg',
170 repo1 = fixture.create_repo('repo1', repo_type='hg',
172 description='diff-test',
171 repo_description='diff-test',
173 owner=TEST_USER_ADMIN_LOGIN)
172 cur_user=TEST_USER_ADMIN_LOGIN)
174 Session().commit()
175 self.r1_id = repo1.repo_id
173 self.r1_id = repo1.repo_id
176
174
177 #commit something !
175 #commit something !
178 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
176 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
179 message='commit1', vcs_type='hg', parent=None,
177 message='commit1', vcs_type='hg', parent=None,
180 newfile=True)
178 newfile=True)
181 cs1 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\n',
179 cs1 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\n',
182 message='commit2', vcs_type='hg', parent=cs0)
180 message='commit2', vcs_type='hg', parent=cs0)
183 #fork this repo
181 #fork this repo
184 repo2 = fixture.create_fork('repo1', 'repo1-fork')
182 repo2 = fixture.create_fork('repo1', 'repo1-fork')
185 self.r2_id = repo2.repo_id
183 self.r2_id = repo2.repo_id
186 #now make cs3-6
184 #now make cs3-6
187 cs2 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\n',
185 cs2 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\n',
188 message='commit3', vcs_type='hg', parent=cs1)
186 message='commit3', vcs_type='hg', parent=cs1)
189 cs3 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\n',
187 cs3 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\n',
190 message='commit4', vcs_type='hg', parent=cs2)
188 message='commit4', vcs_type='hg', parent=cs2)
191 cs4 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\n',
189 cs4 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\n',
192 message='commit5', vcs_type='hg', parent=cs3)
190 message='commit5', vcs_type='hg', parent=cs3)
193 cs5 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\nline6\n',
191 cs5 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\nline6\n',
194 message='commit6', vcs_type='hg', parent=cs4)
192 message='commit6', vcs_type='hg', parent=cs4)
195
193
196 response = self.app.get(url(controller='compare', action='index',
194 response = self.app.get(url(controller='compare', action='index',
197 repo_name=repo2.repo_name,
195 repo_name=repo2.repo_name,
198 org_ref_type="rev",
196 org_ref_type="rev",
199 org_ref=cs1.short_id, # parent of cs2, in repo2
197 org_ref=cs1.short_id, # parent of cs2, in repo2
200 other_repo=repo1.repo_name,
198 other_repo=repo1.repo_name,
201 other_ref_type="rev",
199 other_ref_type="rev",
202 other_ref=cs4.short_id,
200 other_ref=cs4.short_id,
203 merge='True',
201 merge='True',
204 ))
202 ))
205 response.mustcontain('%s@%s -&gt; %s@%s' % (repo2.repo_name, cs1.short_id, repo1.repo_name, cs4.short_id))
203 response.mustcontain('%s@%s -&gt; %s@%s' % (repo2.repo_name, cs1.short_id, repo1.repo_name, cs4.short_id))
206 response.mustcontain("""Showing 3 commits""")
204 response.mustcontain("""Showing 3 commits""")
207 response.mustcontain("""1 file changed with 3 insertions and 0 deletions""")
205 response.mustcontain("""1 file changed with 3 insertions and 0 deletions""")
208
206
209 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
207 response.mustcontain("""<div class="message tooltip" title="commit3" style="white-space:normal">commit3</div>""")
210 response.mustcontain("""<div class="message tooltip" title="commit4" style="white-space:normal">commit4</div>""")
208 response.mustcontain("""<div class="message tooltip" title="commit4" style="white-space:normal">commit4</div>""")
211 response.mustcontain("""<div class="message tooltip" title="commit5" style="white-space:normal">commit5</div>""")
209 response.mustcontain("""<div class="message tooltip" title="commit5" style="white-space:normal">commit5</div>""")
212
210
213 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo1.repo_name, cs2.raw_id, cs2.short_id))
211 response.mustcontain("""<a href="/%s/changeset/%s">r2:%s</a>""" % (repo1.repo_name, cs2.raw_id, cs2.short_id))
214 response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
212 response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
215 response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
213 response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
216 ## files
214 ## files
217 response.mustcontain("""#C--826e8142e6ba">file1</a>""")
215 response.mustcontain("""#C--826e8142e6ba">file1</a>""")
218
216
219 def test_compare_cherry_pick_changesets_from_top(self):
217 def test_compare_cherry_pick_changesets_from_top(self):
220 # repo1:
218 # repo1:
221 # cs0:
219 # cs0:
222 # cs1:
220 # cs1:
223 # repo1-fork- in which we will cherry pick bottom changesets
221 # repo1-fork- in which we will cherry pick bottom changesets
224 # cs0:
222 # cs0:
225 # cs1:
223 # cs1:
226 # cs2:
224 # cs2:
227 # cs3: x
225 # cs3: x
228 # cs4: x
226 # cs4: x
229 # cs5: x
227 # cs5: x
230 #
228 #
231 #make repo1, and cs1+cs2
229 #make repo1, and cs1+cs2
232 self.log_user()
230 self.log_user()
233 repo1 = RepoModel().create_repo(repo_name='repo1', repo_type='hg',
231 repo1 = fixture.create_repo('repo1', repo_type='hg',
234 description='diff-test',
232 repo_description='diff-test',
235 owner=TEST_USER_ADMIN_LOGIN)
233 cur_user=TEST_USER_ADMIN_LOGIN)
236 Session().commit()
237 self.r1_id = repo1.repo_id
234 self.r1_id = repo1.repo_id
238
235
239 #commit something !
236 #commit something !
240 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
237 cs0 = _commit_change(repo1.repo_name, filename='file1', content='line1\n',
241 message='commit1', vcs_type='hg', parent=None,
238 message='commit1', vcs_type='hg', parent=None,
242 newfile=True)
239 newfile=True)
243 cs1 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\n',
240 cs1 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\n',
244 message='commit2', vcs_type='hg', parent=cs0)
241 message='commit2', vcs_type='hg', parent=cs0)
245 #fork this repo
242 #fork this repo
246 repo2 = fixture.create_fork('repo1', 'repo1-fork')
243 repo2 = fixture.create_fork('repo1', 'repo1-fork')
247 self.r2_id = repo2.repo_id
244 self.r2_id = repo2.repo_id
248 #now make cs3-6
245 #now make cs3-6
249 cs2 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\n',
246 cs2 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\n',
250 message='commit3', vcs_type='hg', parent=cs1)
247 message='commit3', vcs_type='hg', parent=cs1)
251 cs3 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\n',
248 cs3 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\n',
252 message='commit4', vcs_type='hg', parent=cs2)
249 message='commit4', vcs_type='hg', parent=cs2)
253 cs4 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\n',
250 cs4 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\n',
254 message='commit5', vcs_type='hg', parent=cs3)
251 message='commit5', vcs_type='hg', parent=cs3)
255 cs5 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\nline6\n',
252 cs5 = _commit_change(repo1.repo_name, filename='file1', content='line1\nline2\nline3\nline4\nline5\nline6\n',
256 message='commit6', vcs_type='hg', parent=cs4)
253 message='commit6', vcs_type='hg', parent=cs4)
257 response = self.app.get(url(controller='compare', action='index',
254 response = self.app.get(url(controller='compare', action='index',
258 repo_name=repo1.repo_name,
255 repo_name=repo1.repo_name,
259 org_ref_type="rev",
256 org_ref_type="rev",
260 org_ref=cs2.short_id, # parent of cs3, not in repo2
257 org_ref=cs2.short_id, # parent of cs3, not in repo2
261 other_ref_type="rev",
258 other_ref_type="rev",
262 other_ref=cs5.short_id,
259 other_ref=cs5.short_id,
263 merge='1',
260 merge='1',
264 ))
261 ))
265
262
266 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, cs2.short_id, repo1.repo_name, cs5.short_id))
263 response.mustcontain('%s@%s -&gt; %s@%s' % (repo1.repo_name, cs2.short_id, repo1.repo_name, cs5.short_id))
267 response.mustcontain("""Showing 3 commits""")
264 response.mustcontain("""Showing 3 commits""")
268 response.mustcontain("""1 file changed with 3 insertions and 0 deletions""")
265 response.mustcontain("""1 file changed with 3 insertions and 0 deletions""")
269
266
270 response.mustcontain("""<div class="message tooltip" title="commit4" style="white-space:normal">commit4</div>""")
267 response.mustcontain("""<div class="message tooltip" title="commit4" style="white-space:normal">commit4</div>""")
271 response.mustcontain("""<div class="message tooltip" title="commit5" style="white-space:normal">commit5</div>""")
268 response.mustcontain("""<div class="message tooltip" title="commit5" style="white-space:normal">commit5</div>""")
272 response.mustcontain("""<div class="message tooltip" title="commit6" style="white-space:normal">commit6</div>""")
269 response.mustcontain("""<div class="message tooltip" title="commit6" style="white-space:normal">commit6</div>""")
273
270
274 response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
271 response.mustcontain("""<a href="/%s/changeset/%s">r3:%s</a>""" % (repo1.repo_name, cs3.raw_id, cs3.short_id))
275 response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
272 response.mustcontain("""<a href="/%s/changeset/%s">r4:%s</a>""" % (repo1.repo_name, cs4.raw_id, cs4.short_id))
276 response.mustcontain("""<a href="/%s/changeset/%s">r5:%s</a>""" % (repo1.repo_name, cs5.raw_id, cs5.short_id))
273 response.mustcontain("""<a href="/%s/changeset/%s">r5:%s</a>""" % (repo1.repo_name, cs5.raw_id, cs5.short_id))
277 ## files
274 ## files
278 response.mustcontain("""#C--826e8142e6ba">file1</a>""")
275 response.mustcontain("""#C--826e8142e6ba">file1</a>""")
279
276
280 def test_compare_cherry_pick_changeset_mixed_branches(self):
277 def test_compare_cherry_pick_changeset_mixed_branches(self):
281 """
282
283 """
284 pass
278 pass
285 #TODO write this tastecase
279 #TODO write this tastecase
286
280
287 def test_compare_remote_branches_hg(self):
281 def test_compare_remote_branches_hg(self):
288 self.log_user()
282 self.log_user()
289
283
290 repo2 = fixture.create_fork(HG_REPO, HG_FORK)
284 repo2 = fixture.create_fork(HG_REPO, HG_FORK)
291 self.r2_id = repo2.repo_id
285 self.r2_id = repo2.repo_id
292 rev1 = '56349e29c2af'
286 rev1 = '56349e29c2af'
293 rev2 = '7d4bc8ec6be5'
287 rev2 = '7d4bc8ec6be5'
294
288
295 response = self.app.get(url(controller='compare', action='index',
289 response = self.app.get(url(controller='compare', action='index',
296 repo_name=HG_REPO,
290 repo_name=HG_REPO,
297 org_ref_type="rev",
291 org_ref_type="rev",
298 org_ref=rev1,
292 org_ref=rev1,
299 other_ref_type="rev",
293 other_ref_type="rev",
300 other_ref=rev2,
294 other_ref=rev2,
301 other_repo=HG_FORK,
295 other_repo=HG_FORK,
302 merge='1',
296 merge='1',
303 ))
297 ))
304 response.mustcontain('%s@%s -&gt; %s@%s' % (HG_REPO, rev1, HG_FORK, rev2))
298 response.mustcontain('%s@%s -&gt; %s@%s' % (HG_REPO, rev1, HG_FORK, rev2))
305 ## outgoing changesets between those revisions
299 ## outgoing changesets between those revisions
306
300
307 response.mustcontain("""<a href="/%s/changeset/2dda4e345facb0ccff1a191052dd1606dba6781d">r4:2dda4e345fac</a>""" % (HG_FORK))
301 response.mustcontain("""<a href="/%s/changeset/2dda4e345facb0ccff1a191052dd1606dba6781d">r4:2dda4e345fac</a>""" % (HG_FORK))
308 response.mustcontain("""<a href="/%s/changeset/6fff84722075f1607a30f436523403845f84cd9e">r5:6fff84722075</a>""" % (HG_FORK))
302 response.mustcontain("""<a href="/%s/changeset/6fff84722075f1607a30f436523403845f84cd9e">r5:6fff84722075</a>""" % (HG_FORK))
309 response.mustcontain("""<a href="/%s/changeset/7d4bc8ec6be56c0f10425afb40b6fc315a4c25e7">r6:%s</a>""" % (HG_FORK, rev2))
303 response.mustcontain("""<a href="/%s/changeset/7d4bc8ec6be56c0f10425afb40b6fc315a4c25e7">r6:%s</a>""" % (HG_FORK, rev2))
310
304
311 ## files
305 ## files
312 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--9c390eb52cd6">vcs/backends/hg.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
306 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--9c390eb52cd6">vcs/backends/hg.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
313 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--41b41c1f2796">vcs/backends/__init__.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
307 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--41b41c1f2796">vcs/backends/__init__.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
314 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--2f574d260608">vcs/backends/base.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
308 response.mustcontain("""<a href="/%s/compare/rev@%s...rev@%s?other_repo=%s&amp;merge=1#C--2f574d260608">vcs/backends/base.py</a>""" % (HG_REPO, rev1, rev2, HG_FORK))
315
309
316 def test_org_repo_new_commits_after_forking_simple_diff(self):
310 def test_org_repo_new_commits_after_forking_simple_diff(self):
317 self.log_user()
311 self.log_user()
318
312
319 repo1 = RepoModel().create_repo(repo_name='one', repo_type='hg',
313 repo1 = fixture.create_repo('one', repo_type='hg',
320 description='diff-test',
314 repo_description='diff-test',
321 owner=TEST_USER_ADMIN_LOGIN)
315 cur_user=TEST_USER_ADMIN_LOGIN)
322
316
323 Session().commit()
324 self.r1_id = repo1.repo_id
317 self.r1_id = repo1.repo_id
325 r1_name = repo1.repo_name
318 r1_name = repo1.repo_name
326
319
327 #commit something initially !
320 #commit something initially !
328 cs0 = ScmModel().create_node(
321 cs0 = ScmModel().create_node(
329 repo=repo1.scm_instance, repo_name=r1_name,
322 repo=repo1.scm_instance, repo_name=r1_name,
330 cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
323 cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
331 author=TEST_USER_ADMIN_LOGIN,
324 author=TEST_USER_ADMIN_LOGIN,
332 message='commit1',
325 message='commit1',
333 content='line1',
326 content='line1',
334 f_path='file1'
327 f_path='file1'
335 )
328 )
336 Session().commit()
329 Session().commit()
337 self.assertEqual(repo1.scm_instance.revisions, [cs0.raw_id])
330 self.assertEqual(repo1.scm_instance.revisions, [cs0.raw_id])
338 #fork the repo1
331 #fork the repo1
339 repo2 = RepoModel().create_repo(repo_name='one-fork', repo_type='hg',
332 repo2 = fixture.create_repo('one-fork', repo_type='hg',
340 description='compare-test',
333 repo_description='diff-test',
341 clone_uri=repo1.repo_full_path,
334 cur_user=TEST_USER_ADMIN_LOGIN,
342 owner=TEST_USER_ADMIN_LOGIN, fork_of='one')
335 clone_uri=repo1.repo_full_path,
336 fork_of='one')
343 Session().commit()
337 Session().commit()
344 self.assertEqual(repo2.scm_instance.revisions, [cs0.raw_id])
338 self.assertEqual(repo2.scm_instance.revisions, [cs0.raw_id])
345 self.r2_id = repo2.repo_id
339 self.r2_id = repo2.repo_id
346 r2_name = repo2.repo_name
340 r2_name = repo2.repo_name
347
341
348 #make 3 new commits in fork
342 #make 3 new commits in fork
349 cs1 = ScmModel().create_node(
343 cs1 = ScmModel().create_node(
350 repo=repo2.scm_instance, repo_name=r2_name,
344 repo=repo2.scm_instance, repo_name=r2_name,
351 cs=repo2.scm_instance[-1], user=TEST_USER_ADMIN_LOGIN,
345 cs=repo2.scm_instance[-1], user=TEST_USER_ADMIN_LOGIN,
352 author=TEST_USER_ADMIN_LOGIN,
346 author=TEST_USER_ADMIN_LOGIN,
353 message='commit1-fork',
347 message='commit1-fork',
354 content='file1-line1-from-fork',
348 content='file1-line1-from-fork',
355 f_path='file1-fork'
349 f_path='file1-fork'
356 )
350 )
357 cs2 = ScmModel().create_node(
351 cs2 = ScmModel().create_node(
358 repo=repo2.scm_instance, repo_name=r2_name,
352 repo=repo2.scm_instance, repo_name=r2_name,
359 cs=cs1, user=TEST_USER_ADMIN_LOGIN,
353 cs=cs1, user=TEST_USER_ADMIN_LOGIN,
360 author=TEST_USER_ADMIN_LOGIN,
354 author=TEST_USER_ADMIN_LOGIN,
361 message='commit2-fork',
355 message='commit2-fork',
362 content='file2-line1-from-fork',
356 content='file2-line1-from-fork',
363 f_path='file2-fork'
357 f_path='file2-fork'
364 )
358 )
365 cs3 = ScmModel().create_node(
359 cs3 = ScmModel().create_node(
366 repo=repo2.scm_instance, repo_name=r2_name,
360 repo=repo2.scm_instance, repo_name=r2_name,
367 cs=cs2, user=TEST_USER_ADMIN_LOGIN,
361 cs=cs2, user=TEST_USER_ADMIN_LOGIN,
368 author=TEST_USER_ADMIN_LOGIN,
362 author=TEST_USER_ADMIN_LOGIN,
369 message='commit3-fork',
363 message='commit3-fork',
370 content='file3-line1-from-fork',
364 content='file3-line1-from-fork',
371 f_path='file3-fork'
365 f_path='file3-fork'
372 )
366 )
373
367
374 #compare !
368 #compare !
375 rev1 = 'default'
369 rev1 = 'default'
376 rev2 = 'default'
370 rev2 = 'default'
377
371
378 response = self.app.get(url(controller='compare', action='index',
372 response = self.app.get(url(controller='compare', action='index',
379 repo_name=r2_name,
373 repo_name=r2_name,
380 org_ref_type="branch",
374 org_ref_type="branch",
381 org_ref=rev1,
375 org_ref=rev1,
382 other_ref_type="branch",
376 other_ref_type="branch",
383 other_ref=rev2,
377 other_ref=rev2,
384 other_repo=r1_name,
378 other_repo=r1_name,
385 merge='1',
379 merge='1',
386 ))
380 ))
387 response.mustcontain('%s@%s -&gt; %s@%s' % (r2_name, rev1, r1_name, rev2))
381 response.mustcontain('%s@%s -&gt; %s@%s' % (r2_name, rev1, r1_name, rev2))
388 response.mustcontain('No files')
382 response.mustcontain('No files')
389 response.mustcontain('No changesets')
383 response.mustcontain('No changesets')
390
384
391 #add new commit into parent !
385 #add new commit into parent !
392 cs0 = ScmModel().create_node(
386 cs0 = ScmModel().create_node(
393 repo=repo1.scm_instance, repo_name=r1_name,
387 repo=repo1.scm_instance, repo_name=r1_name,
394 cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
388 cs=EmptyChangeset(alias='hg'), user=TEST_USER_ADMIN_LOGIN,
395 author=TEST_USER_ADMIN_LOGIN,
389 author=TEST_USER_ADMIN_LOGIN,
396 message='commit2-parent',
390 message='commit2-parent',
397 content='line1-added-after-fork',
391 content='line1-added-after-fork',
398 f_path='file2'
392 f_path='file2'
399 )
393 )
400 #compare !
394 #compare !
401 rev1 = 'default'
395 rev1 = 'default'
402 rev2 = 'default'
396 rev2 = 'default'
403 response = self.app.get(url(controller='compare', action='index',
397 response = self.app.get(url(controller='compare', action='index',
404 repo_name=r2_name,
398 repo_name=r2_name,
405 org_ref_type="branch",
399 org_ref_type="branch",
406 org_ref=rev1,
400 org_ref=rev1,
407 other_ref_type="branch",
401 other_ref_type="branch",
408 other_ref=rev2,
402 other_ref=rev2,
409 other_repo=r1_name,
403 other_repo=r1_name,
410 merge='1',
404 merge='1',
411 ))
405 ))
412
406
413 response.mustcontain('%s@%s -&gt; %s@%s' % (r2_name, rev1, r1_name, rev2))
407 response.mustcontain('%s@%s -&gt; %s@%s' % (r2_name, rev1, r1_name, rev2))
414
408
415 response.mustcontain("""commit2-parent""")
409 response.mustcontain("""commit2-parent""")
416 response.mustcontain("""1 file changed with 1 insertions and 0 deletions""")
410 response.mustcontain("""1 file changed with 1 insertions and 0 deletions""")
417 response.mustcontain("""line1-added-after-fork""")
411 response.mustcontain("""line1-added-after-fork""")
@@ -1,108 +1,111 b''
1 import time
1 import time
2 from rhodecode.tests import *
2 from rhodecode.tests import *
3 from rhodecode.tests.fixture import Fixture
3 from rhodecode.model.meta import Session
4 from rhodecode.model.meta import Session
4 from rhodecode.model.db import User, RhodeCodeSetting, Repository
5 from rhodecode.model.db import User, Repository
5 from rhodecode.lib.utils import set_rhodecode_config
6 from rhodecode.tests.models.common import _make_repo, _make_group
7 from rhodecode.model.repo import RepoModel
6 from rhodecode.model.repo import RepoModel
8 from rhodecode.model.repos_group import ReposGroupModel
7 from rhodecode.model.repos_group import ReposGroupModel
9
8
10
9
10 fixture = Fixture()
11
12
11 class TestHomeController(TestController):
13 class TestHomeController(TestController):
12
14
13 def test_index(self):
15 def test_index(self):
14 self.log_user()
16 self.log_user()
15 response = self.app.get(url(controller='home', action='index'))
17 response = self.app.get(url(controller='home', action='index'))
16 #if global permission is set
18 #if global permission is set
17 response.mustcontain('Add repository')
19 response.mustcontain('Add repository')
18 response.mustcontain('href="/%s"' % HG_REPO)
20 response.mustcontain('href="/%s"' % HG_REPO)
19
21
20 response.mustcontain("""<img class="icon" title="Mercurial repository" """
22 response.mustcontain("""<img class="icon" title="Mercurial repository" """
21 """alt="Mercurial repository" src="/images/icons/hg"""
23 """alt="Mercurial repository" src="/images/icons/hg"""
22 """icon.png"/>""")
24 """icon.png"/>""")
23 response.mustcontain("""<img class="icon" title="public repository" """
25 response.mustcontain("""<img class="icon" title="public repository" """
24 """alt="public repository" src="/images/icons/lock_"""
26 """alt="public repository" src="/images/icons/lock_"""
25 """open.png"/>""")
27 """open.png"/>""")
26
28
27 response.mustcontain(
29 response.mustcontain(
28 """<a title="Marcin Kuzminski &amp;lt;marcin@python-works.com&amp;gt;:\n
30 """<a title="Marcin Kuzminski &amp;lt;marcin@python-works.com&amp;gt;:\n
29 merge" class="tooltip" href="/vcs_test_hg/changeset/27cd5cce30c96924232"""
31 merge" class="tooltip" href="/vcs_test_hg/changeset/27cd5cce30c96924232"""
30 """dffcd24178a07ffeb5dfc">r173:27cd5cce30c9</a>"""
32 """dffcd24178a07ffeb5dfc">r173:27cd5cce30c9</a>"""
31 )
33 )
32
34
33 def test_repo_summary_with_anonymous_access_disabled(self):
35 def test_repo_summary_with_anonymous_access_disabled(self):
34 anon = User.get_by_username('default')
36 anon = User.get_by_username('default')
35 anon.active = False
37 anon.active = False
36 Session().add(anon)
38 Session().add(anon)
37 Session().commit()
39 Session().commit()
38 time.sleep(1.5) # must sleep for cache (1s to expire)
40 time.sleep(1.5) # must sleep for cache (1s to expire)
39 try:
41 try:
40 response = self.app.get(url(controller='summary',
42 response = self.app.get(url(controller='summary',
41 action='index', repo_name=HG_REPO),
43 action='index', repo_name=HG_REPO),
42 status=302)
44 status=302)
43 assert 'login' in response.location
45 assert 'login' in response.location
44
46
45 finally:
47 finally:
46 anon = User.get_by_username('default')
48 anon = User.get_by_username('default')
47 anon.active = True
49 anon.active = True
48 Session().add(anon)
50 Session().add(anon)
49 Session().commit()
51 Session().commit()
50
52
51 def test_index_with_anonymous_access_disabled(self):
53 def test_index_with_anonymous_access_disabled(self):
52 anon = User.get_by_username('default')
54 anon = User.get_by_username('default')
53 anon.active = False
55 anon.active = False
54 Session().add(anon)
56 Session().add(anon)
55 Session().commit()
57 Session().commit()
56 time.sleep(1.5) # must sleep for cache (1s to expire)
58 time.sleep(1.5) # must sleep for cache (1s to expire)
57 try:
59 try:
58 response = self.app.get(url(controller='home', action='index'),
60 response = self.app.get(url(controller='home', action='index'),
59 status=302)
61 status=302)
60 assert 'login' in response.location
62 assert 'login' in response.location
61 finally:
63 finally:
62 anon = User.get_by_username('default')
64 anon = User.get_by_username('default')
63 anon.active = True
65 anon.active = True
64 Session().add(anon)
66 Session().add(anon)
65 Session().commit()
67 Session().commit()
66
68
67 def _set_l_dash(self, set_to):
69 def _set_l_dash(self, set_to):
68 self.app.post(url('admin_setting', setting_id='visual'),
70 self.app.post(url('admin_setting', setting_id='visual'),
69 params=dict(_method='put',
71 params=dict(_method='put',
70 rhodecode_lightweight_dashboard=set_to,))
72 rhodecode_lightweight_dashboard=set_to,))
71
73
72 def test_index_with_lightweight_dashboard(self):
74 def test_index_with_lightweight_dashboard(self):
73 self.log_user()
75 self.log_user()
74 self._set_l_dash(True)
76 self._set_l_dash(True)
75
77
76 try:
78 try:
77 response = self.app.get(url(controller='home', action='index'))
79 response = self.app.get(url(controller='home', action='index'))
78 response.mustcontain("""var data = {"totalRecords": %s""" % len(Repository.getAll()))
80 response.mustcontain("""var data = {"totalRecords": %s"""
81 % len(Repository.getAll()))
79 finally:
82 finally:
80 self._set_l_dash(False)
83 self._set_l_dash(False)
81
84
82 def test_index_page_on_groups(self):
85 def test_index_page_on_groups(self):
83 self.log_user()
86 self.log_user()
84 _make_repo(name='gr1/repo_in_group', repos_group=_make_group('gr1'))
87 gr = fixture.create_group('gr1')
85 Session().commit()
88 fixture.create_repo(name='gr1/repo_in_group', repos_group=gr)
86 response = self.app.get(url('repos_group_home', group_name='gr1'))
89 response = self.app.get(url('repos_group_home', group_name='gr1'))
87
90
88 try:
91 try:
89 response.mustcontain("""gr1/repo_in_group""")
92 response.mustcontain("gr1/repo_in_group")
90 finally:
93 finally:
91 RepoModel().delete('gr1/repo_in_group')
94 RepoModel().delete('gr1/repo_in_group')
92 ReposGroupModel().delete(repos_group='gr1', force_delete=True)
95 ReposGroupModel().delete(repos_group='gr1', force_delete=True)
93 Session().commit()
96 Session().commit()
94
97
95 def test_index_page_on_groups_with_lightweight_dashboard(self):
98 def test_index_page_on_groups_with_lightweight_dashboard(self):
96 self.log_user()
99 self.log_user()
97 self._set_l_dash(True)
100 self._set_l_dash(True)
98 _make_repo(name='gr1/repo_in_group', repos_group=_make_group('gr1'))
101 fixture.create_repo(name='gr1/repo_in_group',
99 Session().commit()
102 repos_group=fixture.create_group('gr1'))
100 response = self.app.get(url('repos_group_home', group_name='gr1'))
103 response = self.app.get(url('repos_group_home', group_name='gr1'))
101
104
102 try:
105 try:
103 response.mustcontain("""gr1/repo_in_group""")
106 response.mustcontain("""gr1/repo_in_group""")
104 finally:
107 finally:
105 self._set_l_dash(False)
108 self._set_l_dash(False)
106 RepoModel().delete('gr1/repo_in_group')
109 RepoModel().delete('gr1/repo_in_group')
107 ReposGroupModel().delete(repos_group='gr1', force_delete=True)
110 ReposGroupModel().delete(repos_group='gr1', force_delete=True)
108 Session().commit()
111 Session().commit()
@@ -1,121 +1,122 b''
1 from rhodecode.tests import *
1 from rhodecode.tests import *
2 from rhodecode.tests.fixture import Fixture
2 from rhodecode.model.db import Repository
3 from rhodecode.model.db import Repository
3 from rhodecode.lib.utils import invalidate_cache
4 from rhodecode.lib.utils import invalidate_cache
4 from rhodecode.model.repo import RepoModel
5 from rhodecode.model.repo import RepoModel
5 from rhodecode.tests.models.common import _make_repo
6 from rhodecode.model.meta import Session
6 from rhodecode.model.meta import Session
7
7
8 fixture = Fixture()
9
8
10
9 class TestSummaryController(TestController):
11 class TestSummaryController(TestController):
10
12
11 def test_index(self):
13 def test_index(self):
12 self.log_user()
14 self.log_user()
13 ID = Repository.get_by_repo_name(HG_REPO).repo_id
15 ID = Repository.get_by_repo_name(HG_REPO).repo_id
14 response = self.app.get(url(controller='summary',
16 response = self.app.get(url(controller='summary',
15 action='index',
17 action='index',
16 repo_name=HG_REPO))
18 repo_name=HG_REPO))
17
19
18 #repo type
20 #repo type
19 response.mustcontain(
21 response.mustcontain(
20 """<img style="margin-bottom:2px" class="icon" """
22 """<img style="margin-bottom:2px" class="icon" """
21 """title="Mercurial repository" alt="Mercurial repository" """
23 """title="Mercurial repository" alt="Mercurial repository" """
22 """src="/images/icons/hgicon.png"/>"""
24 """src="/images/icons/hgicon.png"/>"""
23 )
25 )
24 response.mustcontain(
26 response.mustcontain(
25 """<img style="margin-bottom:2px" class="icon" """
27 """<img style="margin-bottom:2px" class="icon" """
26 """title="public repository" alt="public """
28 """title="public repository" alt="public """
27 """repository" src="/images/icons/lock_open.png"/>"""
29 """repository" src="/images/icons/lock_open.png"/>"""
28 )
30 )
29
31
30 #codes stats
32 #codes stats
31 self._enable_stats()
33 self._enable_stats()
32
34
33 invalidate_cache('get_repo_cached_%s' % HG_REPO)
35 invalidate_cache('get_repo_cached_%s' % HG_REPO)
34 response = self.app.get(url(controller='summary', action='index',
36 response = self.app.get(url(controller='summary', action='index',
35 repo_name=HG_REPO))
37 repo_name=HG_REPO))
36 response.mustcontain(
38 response.mustcontain(
37 """var data = [["py", {"count": 42, "desc": ["Python"]}], """
39 """var data = [["py", {"count": 42, "desc": ["Python"]}], """
38 """["rst", {"count": 11, "desc": ["Rst"]}], """
40 """["rst", {"count": 11, "desc": ["Rst"]}], """
39 """["sh", {"count": 2, "desc": ["Bash"]}], """
41 """["sh", {"count": 2, "desc": ["Bash"]}], """
40 """["makefile", {"count": 1, "desc": ["Makefile", "Makefile"]}],"""
42 """["makefile", {"count": 1, "desc": ["Makefile", "Makefile"]}],"""
41 """ ["cfg", {"count": 1, "desc": ["Ini"]}], """
43 """ ["cfg", {"count": 1, "desc": ["Ini"]}], """
42 """["css", {"count": 1, "desc": ["Css"]}], """
44 """["css", {"count": 1, "desc": ["Css"]}], """
43 """["bat", {"count": 1, "desc": ["Batch"]}]];"""
45 """["bat", {"count": 1, "desc": ["Batch"]}]];"""
44 )
46 )
45
47
46 # clone url...
48 # clone url...
47 response.mustcontain('''id="clone_url" readonly="readonly" value="http://test_admin@localhost:80/%s"''' % HG_REPO)
49 response.mustcontain('''id="clone_url" readonly="readonly" value="http://test_admin@localhost:80/%s"''' % HG_REPO)
48 response.mustcontain('''id="clone_url_id" readonly="readonly" value="http://test_admin@localhost:80/_%s"''' % ID)
50 response.mustcontain('''id="clone_url_id" readonly="readonly" value="http://test_admin@localhost:80/_%s"''' % ID)
49
51
50 def test_index_git(self):
52 def test_index_git(self):
51 self.log_user()
53 self.log_user()
52 ID = Repository.get_by_repo_name(GIT_REPO).repo_id
54 ID = Repository.get_by_repo_name(GIT_REPO).repo_id
53 response = self.app.get(url(controller='summary',
55 response = self.app.get(url(controller='summary',
54 action='index',
56 action='index',
55 repo_name=GIT_REPO))
57 repo_name=GIT_REPO))
56
58
57 #repo type
59 #repo type
58 response.mustcontain(
60 response.mustcontain(
59 """<img style="margin-bottom:2px" class="icon" """
61 """<img style="margin-bottom:2px" class="icon" """
60 """title="Git repository" alt="Git repository" """
62 """title="Git repository" alt="Git repository" """
61 """src="/images/icons/giticon.png"/>"""
63 """src="/images/icons/giticon.png"/>"""
62 )
64 )
63 response.mustcontain(
65 response.mustcontain(
64 """<img style="margin-bottom:2px" class="icon" """
66 """<img style="margin-bottom:2px" class="icon" """
65 """title="public repository" alt="public """
67 """title="public repository" alt="public """
66 """repository" src="/images/icons/lock_open.png"/>"""
68 """repository" src="/images/icons/lock_open.png"/>"""
67 )
69 )
68
70
69 # clone url...
71 # clone url...
70 response.mustcontain('''id="clone_url" readonly="readonly" value="http://test_admin@localhost:80/%s"''' % GIT_REPO)
72 response.mustcontain('''id="clone_url" readonly="readonly" value="http://test_admin@localhost:80/%s"''' % GIT_REPO)
71 response.mustcontain('''id="clone_url_id" readonly="readonly" value="http://test_admin@localhost:80/_%s"''' % ID)
73 response.mustcontain('''id="clone_url_id" readonly="readonly" value="http://test_admin@localhost:80/_%s"''' % ID)
72
74
73 def test_index_by_id_hg(self):
75 def test_index_by_id_hg(self):
74 self.log_user()
76 self.log_user()
75 ID = Repository.get_by_repo_name(HG_REPO).repo_id
77 ID = Repository.get_by_repo_name(HG_REPO).repo_id
76 response = self.app.get(url(controller='summary',
78 response = self.app.get(url(controller='summary',
77 action='index',
79 action='index',
78 repo_name='_%s' % ID))
80 repo_name='_%s' % ID))
79
81
80 #repo type
82 #repo type
81 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
83 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
82 """title="Mercurial repository" alt="Mercurial """
84 """title="Mercurial repository" alt="Mercurial """
83 """repository" src="/images/icons/hgicon.png"/>""")
85 """repository" src="/images/icons/hgicon.png"/>""")
84 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
86 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
85 """title="public repository" alt="public """
87 """title="public repository" alt="public """
86 """repository" src="/images/icons/lock_open.png"/>""")
88 """repository" src="/images/icons/lock_open.png"/>""")
87
89
88 def test_index_by_repo_having_id_path_in_name_hg(self):
90 def test_index_by_repo_having_id_path_in_name_hg(self):
89 self.log_user()
91 self.log_user()
90 _make_repo(name='repo_1')
92 fixture.create_repo(name='repo_1')
91 Session().commit()
92 response = self.app.get(url(controller='summary',
93 response = self.app.get(url(controller='summary',
93 action='index',
94 action='index',
94 repo_name='repo_1'))
95 repo_name='repo_1'))
95
96
96 try:
97 try:
97 response.mustcontain("""repo_1""")
98 response.mustcontain("repo_1")
98 finally:
99 finally:
99 RepoModel().delete(Repository.get_by_repo_name('repo_1'))
100 RepoModel().delete(Repository.get_by_repo_name('repo_1'))
100 Session().commit()
101 Session().commit()
101
102
102 def test_index_by_id_git(self):
103 def test_index_by_id_git(self):
103 self.log_user()
104 self.log_user()
104 ID = Repository.get_by_repo_name(GIT_REPO).repo_id
105 ID = Repository.get_by_repo_name(GIT_REPO).repo_id
105 response = self.app.get(url(controller='summary',
106 response = self.app.get(url(controller='summary',
106 action='index',
107 action='index',
107 repo_name='_%s' % ID))
108 repo_name='_%s' % ID))
108
109
109 #repo type
110 #repo type
110 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
111 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
111 """title="Git repository" alt="Git """
112 """title="Git repository" alt="Git """
112 """repository" src="/images/icons/giticon.png"/>""")
113 """repository" src="/images/icons/giticon.png"/>""")
113 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
114 response.mustcontain("""<img style="margin-bottom:2px" class="icon" """
114 """title="public repository" alt="public """
115 """title="public repository" alt="public """
115 """repository" src="/images/icons/lock_open.png"/>""")
116 """repository" src="/images/icons/lock_open.png"/>""")
116
117
117 def _enable_stats(self):
118 def _enable_stats(self):
118 r = Repository.get_by_repo_name(HG_REPO)
119 r = Repository.get_by_repo_name(HG_REPO)
119 r.enable_statistics = True
120 r.enable_statistics = True
120 self.Session.add(r)
121 self.Session.add(r)
121 self.Session.commit()
122 self.Session.commit()
@@ -1,120 +1,104 b''
1 import os
1 import os
2 import unittest
2 import unittest
3 import functools
3 import functools
4 from rhodecode.tests import *
4 from rhodecode.tests import *
5
5 from rhodecode.tests.fixture import Fixture
6
6
7 from rhodecode.model.repos_group import ReposGroupModel
7 from rhodecode.model.repos_group import ReposGroupModel
8 from rhodecode.model.repo import RepoModel
8 from rhodecode.model.repo import RepoModel
9 from rhodecode.model.db import RepoGroup, Repository, User
9 from rhodecode.model.db import RepoGroup, Repository, User
10 from rhodecode.model.user import UserModel
10 from rhodecode.model.user import UserModel
11
11
12 from rhodecode.lib.auth import AuthUser
12 from rhodecode.lib.auth import AuthUser
13 from rhodecode.model.meta import Session
13 from rhodecode.model.meta import Session
14
14
15
15
16 def _make_group(path, desc='desc', parent_id=None,
16 fixture = Fixture()
17 skip_if_exists=False):
18
19 gr = RepoGroup.get_by_group_name(path)
20 if gr and skip_if_exists:
21 return gr
22 if isinstance(parent_id, RepoGroup):
23 parent_id = parent_id.group_id
24 gr = ReposGroupModel().create(path, desc, TEST_USER_ADMIN_LOGIN, parent_id)
25 return gr
26
27
28 def _make_repo(name, repos_group=None, repo_type='hg', private=False):
29 return RepoModel().create_repo(name, repo_type, 'desc',
30 TEST_USER_ADMIN_LOGIN,
31 repos_group=repos_group,
32 private=private)
33
17
34
18
35 def _destroy_project_tree(test_u1_id):
19 def _destroy_project_tree(test_u1_id):
36 Session.remove()
20 Session.remove()
37 repos_group = RepoGroup.get_by_group_name(group_name='g0')
21 repos_group = RepoGroup.get_by_group_name(group_name='g0')
38 for el in reversed(repos_group.recursive_groups_and_repos()):
22 for el in reversed(repos_group.recursive_groups_and_repos()):
39 if isinstance(el, Repository):
23 if isinstance(el, Repository):
40 RepoModel().delete(el)
24 RepoModel().delete(el)
41 elif isinstance(el, RepoGroup):
25 elif isinstance(el, RepoGroup):
42 ReposGroupModel().delete(el, force_delete=True)
26 ReposGroupModel().delete(el, force_delete=True)
43
27
44 u = User.get(test_u1_id)
28 u = User.get(test_u1_id)
45 Session().delete(u)
29 Session().delete(u)
46 Session().commit()
30 Session().commit()
47
31
48
32
49 def _create_project_tree():
33 def _create_project_tree():
50 """
34 """
51 Creates a tree of groups and repositories to test permissions
35 Creates a tree of groups and repositories to test permissions
52
36
53 structure
37 structure
54 [g0] - group `g0` with 3 subgroups
38 [g0] - group `g0` with 3 subgroups
55 |
39 |
56 |__[g0_1] group g0_1 with 2 groups 0 repos
40 |__[g0_1] group g0_1 with 2 groups 0 repos
57 | |
41 | |
58 | |__[g0_1_1] group g0_1_1 with 1 group 2 repos
42 | |__[g0_1_1] group g0_1_1 with 1 group 2 repos
59 | | |__<g0/g0_1/g0_1_1/g0_1_1_r1>
43 | | |__<g0/g0_1/g0_1_1/g0_1_1_r1>
60 | | |__<g0/g0_1/g0_1_1/g0_1_1_r2>
44 | | |__<g0/g0_1/g0_1_1/g0_1_1_r2>
61 | |__<g0/g0_1/g0_1_r1>
45 | |__<g0/g0_1/g0_1_r1>
62 |
46 |
63 |__[g0_2] 2 repos
47 |__[g0_2] 2 repos
64 | |
48 | |
65 | |__<g0/g0_2/g0_2_r1>
49 | |__<g0/g0_2/g0_2_r1>
66 | |__<g0/g0_2/g0_2_r2>
50 | |__<g0/g0_2/g0_2_r2>
67 |
51 |
68 |__[g0_3] 1 repo
52 |__[g0_3] 1 repo
69 |
53 |
70 |_<g0/g0_3/g0_3_r1>
54 |_<g0/g0_3/g0_3_r1>
71 |_<g0/g0_3/g0_3_r2_private>
55 |_<g0/g0_3/g0_3_r2_private>
72
56
73 """
57 """
74 test_u1 = UserModel().create_or_update(
58 test_u1 = UserModel().create_or_update(
75 username=u'test_u1', password=u'qweqwe',
59 username=u'test_u1', password=u'qweqwe',
76 email=u'test_u1@rhodecode.org', firstname=u'test_u1', lastname=u'test_u1'
60 email=u'test_u1@rhodecode.org', firstname=u'test_u1', lastname=u'test_u1'
77 )
61 )
78 g0 = _make_group('g0')
62 g0 = fixture.create_group('g0')
79 g0_1 = _make_group('g0_1', parent_id=g0)
63 g0_1 = fixture.create_group('g0_1', group_parent_id=g0)
80 g0_1_1 = _make_group('g0_1_1', parent_id=g0_1)
64 g0_1_1 = fixture.create_group('g0_1_1', group_parent_id=g0_1)
81 g0_1_1_r1 = _make_repo('g0/g0_1/g0_1_1/g0_1_1_r1', repos_group=g0_1_1)
65 g0_1_1_r1 = fixture.create_repo('g0/g0_1/g0_1_1/g0_1_1_r1', repos_group=g0_1_1)
82 g0_1_1_r2 = _make_repo('g0/g0_1/g0_1_1/g0_1_1_r2', repos_group=g0_1_1)
66 g0_1_1_r2 = fixture.create_repo('g0/g0_1/g0_1_1/g0_1_1_r2', repos_group=g0_1_1)
83 g0_1_r1 = _make_repo('g0/g0_1/g0_1_r1', repos_group=g0_1)
67 g0_1_r1 = fixture.create_repo('g0/g0_1/g0_1_r1', repos_group=g0_1)
84 g0_2 = _make_group('g0_2', parent_id=g0)
68 g0_2 = fixture.create_group('g0_2', group_parent_id=g0)
85 g0_2_r1 = _make_repo('g0/g0_2/g0_2_r1', repos_group=g0_2)
69 g0_2_r1 = fixture.create_repo('g0/g0_2/g0_2_r1', repos_group=g0_2)
86 g0_2_r2 = _make_repo('g0/g0_2/g0_2_r2', repos_group=g0_2)
70 g0_2_r2 = fixture.create_repo('g0/g0_2/g0_2_r2', repos_group=g0_2)
87 g0_3 = _make_group('g0_3', parent_id=g0)
71 g0_3 = fixture.create_group('g0_3', group_parent_id=g0)
88 g0_3_r1 = _make_repo('g0/g0_3/g0_3_r1', repos_group=g0_3)
72 g0_3_r1 = fixture.create_repo('g0/g0_3/g0_3_r1', repos_group=g0_3)
89 g0_3_r2_private = _make_repo('g0/g0_3/g0_3_r1_private', repos_group=g0_3,
73 g0_3_r2_private = fixture.create_repo('g0/g0_3/g0_3_r1_private',
90 private=True)
74 repos_group=g0_3, repo_private=True)
91 return test_u1
75 return test_u1
92
76
93
77
94 def expected_count(group_name, objects=False):
78 def expected_count(group_name, objects=False):
95 repos_group = RepoGroup.get_by_group_name(group_name=group_name)
79 repos_group = RepoGroup.get_by_group_name(group_name=group_name)
96 objs = repos_group.recursive_groups_and_repos()
80 objs = repos_group.recursive_groups_and_repos()
97 if objects:
81 if objects:
98 return objs
82 return objs
99 return len(objs)
83 return len(objs)
100
84
101
85
102 def _check_expected_count(items, repo_items, expected):
86 def _check_expected_count(items, repo_items, expected):
103 should_be = len(items + repo_items)
87 should_be = len(items + repo_items)
104 there_are = len(expected)
88 there_are = len(expected)
105 assert should_be == there_are, ('%s != %s' % ((items + repo_items), expected))
89 assert should_be == there_are, ('%s != %s' % ((items + repo_items), expected))
106
90
107
91
108 def check_tree_perms(obj_name, repo_perm, prefix, expected_perm):
92 def check_tree_perms(obj_name, repo_perm, prefix, expected_perm):
109 assert repo_perm == expected_perm, ('obj:`%s` got perm:`%s` should:`%s`'
93 assert repo_perm == expected_perm, ('obj:`%s` got perm:`%s` should:`%s`'
110 % (obj_name, repo_perm, expected_perm))
94 % (obj_name, repo_perm, expected_perm))
111
95
112
96
113 def _get_perms(filter_='', recursive=True, key=None, test_u1_id=None):
97 def _get_perms(filter_='', recursive=True, key=None, test_u1_id=None):
114 test_u1 = AuthUser(user_id=test_u1_id)
98 test_u1 = AuthUser(user_id=test_u1_id)
115 for k, v in test_u1.permissions[key].items():
99 for k, v in test_u1.permissions[key].items():
116 if recursive and k.startswith(filter_):
100 if recursive and k.startswith(filter_):
117 yield k, v
101 yield k, v
118 elif not recursive:
102 elif not recursive:
119 if k == filter_:
103 if k == filter_:
120 yield k, v
104 yield k, v
@@ -1,472 +1,465 b''
1 import os
1 import os
2 import unittest
2 import unittest
3 from rhodecode.tests import *
3 from rhodecode.tests import *
4 from rhodecode.tests.models.common import _make_group
4 from rhodecode.tests.fixture import Fixture
5 from rhodecode.model.repos_group import ReposGroupModel
5 from rhodecode.model.repos_group import ReposGroupModel
6 from rhodecode.model.repo import RepoModel
6 from rhodecode.model.repo import RepoModel
7 from rhodecode.model.db import RepoGroup, User, UserGroupRepoGroupToPerm
7 from rhodecode.model.db import RepoGroup, User, UserGroupRepoGroupToPerm
8 from rhodecode.model.user import UserModel
8 from rhodecode.model.user import UserModel
9
9
10 from rhodecode.model.meta import Session
10 from rhodecode.model.meta import Session
11 from rhodecode.model.users_group import UserGroupModel
11 from rhodecode.model.users_group import UserGroupModel
12 from rhodecode.lib.auth import AuthUser
12 from rhodecode.lib.auth import AuthUser
13 from rhodecode.tests.api.api_base import create_repo
13
14
15 fixture = Fixture()
14
16
15
17
16 class TestPermissions(unittest.TestCase):
18 class TestPermissions(unittest.TestCase):
17 def __init__(self, methodName='runTest'):
19 def __init__(self, methodName='runTest'):
18 super(TestPermissions, self).__init__(methodName=methodName)
20 super(TestPermissions, self).__init__(methodName=methodName)
19
21
20 def setUp(self):
22 def setUp(self):
21 self.u1 = UserModel().create_or_update(
23 self.u1 = UserModel().create_or_update(
22 username=u'u1', password=u'qweqwe',
24 username=u'u1', password=u'qweqwe',
23 email=u'u1@rhodecode.org', firstname=u'u1', lastname=u'u1'
25 email=u'u1@rhodecode.org', firstname=u'u1', lastname=u'u1'
24 )
26 )
25 self.u2 = UserModel().create_or_update(
27 self.u2 = UserModel().create_or_update(
26 username=u'u2', password=u'qweqwe',
28 username=u'u2', password=u'qweqwe',
27 email=u'u2@rhodecode.org', firstname=u'u2', lastname=u'u2'
29 email=u'u2@rhodecode.org', firstname=u'u2', lastname=u'u2'
28 )
30 )
29 self.u3 = UserModel().create_or_update(
31 self.u3 = UserModel().create_or_update(
30 username=u'u3', password=u'qweqwe',
32 username=u'u3', password=u'qweqwe',
31 email=u'u3@rhodecode.org', firstname=u'u3', lastname=u'u3'
33 email=u'u3@rhodecode.org', firstname=u'u3', lastname=u'u3'
32 )
34 )
33 self.anon = User.get_by_username('default')
35 self.anon = User.get_by_username('default')
34 self.a1 = UserModel().create_or_update(
36 self.a1 = UserModel().create_or_update(
35 username=u'a1', password=u'qweqwe',
37 username=u'a1', password=u'qweqwe',
36 email=u'a1@rhodecode.org', firstname=u'a1', lastname=u'a1', admin=True
38 email=u'a1@rhodecode.org', firstname=u'a1', lastname=u'a1', admin=True
37 )
39 )
38 Session().commit()
40 Session().commit()
39
41
40 def tearDown(self):
42 def tearDown(self):
41 if hasattr(self, 'test_repo'):
43 if hasattr(self, 'test_repo'):
42 RepoModel().delete(repo=self.test_repo)
44 RepoModel().delete(repo=self.test_repo)
43
45
44 UserModel().delete(self.u1)
46 UserModel().delete(self.u1)
45 UserModel().delete(self.u2)
47 UserModel().delete(self.u2)
46 UserModel().delete(self.u3)
48 UserModel().delete(self.u3)
47 UserModel().delete(self.a1)
49 UserModel().delete(self.a1)
48 if hasattr(self, 'g1'):
50 if hasattr(self, 'g1'):
49 ReposGroupModel().delete(self.g1.group_id)
51 ReposGroupModel().delete(self.g1.group_id)
50 if hasattr(self, 'g2'):
52 if hasattr(self, 'g2'):
51 ReposGroupModel().delete(self.g2.group_id)
53 ReposGroupModel().delete(self.g2.group_id)
52
54
53 if hasattr(self, 'ug1'):
55 if hasattr(self, 'ug1'):
54 UserGroupModel().delete(self.ug1, force=True)
56 UserGroupModel().delete(self.ug1, force=True)
55
57
56 Session().commit()
58 Session().commit()
57
59
58 def test_default_perms_set(self):
60 def test_default_perms_set(self):
59 u1_auth = AuthUser(user_id=self.u1.user_id)
61 u1_auth = AuthUser(user_id=self.u1.user_id)
60 perms = {
62 perms = {
61 'repositories_groups': {},
63 'repositories_groups': {},
62 'global': set([u'hg.create.repository', u'repository.read',
64 'global': set([u'hg.create.repository', u'repository.read',
63 u'hg.register.manual_activate']),
65 u'hg.register.manual_activate']),
64 'repositories': {u'vcs_test_hg': u'repository.read'}
66 'repositories': {u'vcs_test_hg': u'repository.read'}
65 }
67 }
66 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
68 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
67 perms['repositories'][HG_REPO])
69 perms['repositories'][HG_REPO])
68 new_perm = 'repository.write'
70 new_perm = 'repository.write'
69 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
71 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
70 perm=new_perm)
72 perm=new_perm)
71 Session().commit()
73 Session().commit()
72
74
73 u1_auth = AuthUser(user_id=self.u1.user_id)
75 u1_auth = AuthUser(user_id=self.u1.user_id)
74 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
76 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
75 new_perm)
77 new_perm)
76
78
77 def test_default_admin_perms_set(self):
79 def test_default_admin_perms_set(self):
78 a1_auth = AuthUser(user_id=self.a1.user_id)
80 a1_auth = AuthUser(user_id=self.a1.user_id)
79 perms = {
81 perms = {
80 'repositories_groups': {},
82 'repositories_groups': {},
81 'global': set([u'hg.admin']),
83 'global': set([u'hg.admin']),
82 'repositories': {u'vcs_test_hg': u'repository.admin'}
84 'repositories': {u'vcs_test_hg': u'repository.admin'}
83 }
85 }
84 self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
86 self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
85 perms['repositories'][HG_REPO])
87 perms['repositories'][HG_REPO])
86 new_perm = 'repository.write'
88 new_perm = 'repository.write'
87 RepoModel().grant_user_permission(repo=HG_REPO, user=self.a1,
89 RepoModel().grant_user_permission(repo=HG_REPO, user=self.a1,
88 perm=new_perm)
90 perm=new_perm)
89 Session().commit()
91 Session().commit()
90 # cannot really downgrade admins permissions !? they still get's set as
92 # cannot really downgrade admins permissions !? they still get's set as
91 # admin !
93 # admin !
92 u1_auth = AuthUser(user_id=self.a1.user_id)
94 u1_auth = AuthUser(user_id=self.a1.user_id)
93 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
95 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
94 perms['repositories'][HG_REPO])
96 perms['repositories'][HG_REPO])
95
97
96 def test_default_group_perms(self):
98 def test_default_group_perms(self):
97 self.g1 = _make_group('test1', skip_if_exists=True)
99 self.g1 = fixture.create_group('test1', skip_if_exists=True)
98 self.g2 = _make_group('test2', skip_if_exists=True)
100 self.g2 = fixture.create_group('test2', skip_if_exists=True)
99 u1_auth = AuthUser(user_id=self.u1.user_id)
101 u1_auth = AuthUser(user_id=self.u1.user_id)
100 perms = {
102 perms = {
101 'repositories_groups': {u'test1': 'group.read', u'test2': 'group.read'},
103 'repositories_groups': {u'test1': 'group.read', u'test2': 'group.read'},
102 'global': set([u'hg.create.repository', u'repository.read', u'hg.register.manual_activate']),
104 'global': set([u'hg.create.repository', u'repository.read', u'hg.register.manual_activate']),
103 'repositories': {u'vcs_test_hg': u'repository.read'}
105 'repositories': {u'vcs_test_hg': u'repository.read'}
104 }
106 }
105 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
107 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
106 perms['repositories'][HG_REPO])
108 perms['repositories'][HG_REPO])
107 self.assertEqual(u1_auth.permissions['repositories_groups'],
109 self.assertEqual(u1_auth.permissions['repositories_groups'],
108 perms['repositories_groups'])
110 perms['repositories_groups'])
109
111
110 def test_default_admin_group_perms(self):
112 def test_default_admin_group_perms(self):
111 self.g1 = _make_group('test1', skip_if_exists=True)
113 self.g1 = fixture.create_group('test1', skip_if_exists=True)
112 self.g2 = _make_group('test2', skip_if_exists=True)
114 self.g2 = fixture.create_group('test2', skip_if_exists=True)
113 a1_auth = AuthUser(user_id=self.a1.user_id)
115 a1_auth = AuthUser(user_id=self.a1.user_id)
114 perms = {
116 perms = {
115 'repositories_groups': {u'test1': 'group.admin', u'test2': 'group.admin'},
117 'repositories_groups': {u'test1': 'group.admin', u'test2': 'group.admin'},
116 'global': set(['hg.admin']),
118 'global': set(['hg.admin']),
117 'repositories': {u'vcs_test_hg': 'repository.admin'}
119 'repositories': {u'vcs_test_hg': 'repository.admin'}
118 }
120 }
119
121
120 self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
122 self.assertEqual(a1_auth.permissions['repositories'][HG_REPO],
121 perms['repositories'][HG_REPO])
123 perms['repositories'][HG_REPO])
122 self.assertEqual(a1_auth.permissions['repositories_groups'],
124 self.assertEqual(a1_auth.permissions['repositories_groups'],
123 perms['repositories_groups'])
125 perms['repositories_groups'])
124
126
125 def test_propagated_permission_from_users_group_by_explicit_perms_exist(self):
127 def test_propagated_permission_from_users_group_by_explicit_perms_exist(self):
126 # make group
128 # make group
127 self.ug1 = UserGroupModel().create('G1')
129 self.ug1 = UserGroupModel().create('G1')
128 # add user to group
130 # add user to group
129
131
130 UserGroupModel().add_user_to_group(self.ug1, self.u1)
132 UserGroupModel().add_user_to_group(self.ug1, self.u1)
131
133
132 # set permission to lower
134 # set permission to lower
133 new_perm = 'repository.none'
135 new_perm = 'repository.none'
134 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1, perm=new_perm)
136 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1, perm=new_perm)
135 Session().commit()
137 Session().commit()
136 u1_auth = AuthUser(user_id=self.u1.user_id)
138 u1_auth = AuthUser(user_id=self.u1.user_id)
137 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
139 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
138 new_perm)
140 new_perm)
139
141
140 # grant perm for group this should not override permission from user
142 # grant perm for group this should not override permission from user
141 # since it has explicitly set
143 # since it has explicitly set
142 new_perm_gr = 'repository.write'
144 new_perm_gr = 'repository.write'
143 RepoModel().grant_users_group_permission(repo=HG_REPO,
145 RepoModel().grant_users_group_permission(repo=HG_REPO,
144 group_name=self.ug1,
146 group_name=self.ug1,
145 perm=new_perm_gr)
147 perm=new_perm_gr)
146 # check perms
148 # check perms
147 u1_auth = AuthUser(user_id=self.u1.user_id)
149 u1_auth = AuthUser(user_id=self.u1.user_id)
148 perms = {
150 perms = {
149 'repositories_groups': {},
151 'repositories_groups': {},
150 'global': set([u'hg.create.repository', u'repository.read',
152 'global': set([u'hg.create.repository', u'repository.read',
151 u'hg.register.manual_activate']),
153 u'hg.register.manual_activate']),
152 'repositories': {u'vcs_test_hg': u'repository.read'}
154 'repositories': {u'vcs_test_hg': u'repository.read'}
153 }
155 }
154 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
156 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
155 new_perm)
157 new_perm)
156 self.assertEqual(u1_auth.permissions['repositories_groups'],
158 self.assertEqual(u1_auth.permissions['repositories_groups'],
157 perms['repositories_groups'])
159 perms['repositories_groups'])
158
160
159 def test_propagated_permission_from_users_group(self):
161 def test_propagated_permission_from_users_group(self):
160 # make group
162 # make group
161 self.ug1 = UserGroupModel().create('G1')
163 self.ug1 = UserGroupModel().create('G1')
162 # add user to group
164 # add user to group
163
165
164 UserGroupModel().add_user_to_group(self.ug1, self.u3)
166 UserGroupModel().add_user_to_group(self.ug1, self.u3)
165
167
166 # grant perm for group this should override default permission from user
168 # grant perm for group this should override default permission from user
167 new_perm_gr = 'repository.write'
169 new_perm_gr = 'repository.write'
168 RepoModel().grant_users_group_permission(repo=HG_REPO,
170 RepoModel().grant_users_group_permission(repo=HG_REPO,
169 group_name=self.ug1,
171 group_name=self.ug1,
170 perm=new_perm_gr)
172 perm=new_perm_gr)
171 # check perms
173 # check perms
172 u3_auth = AuthUser(user_id=self.u3.user_id)
174 u3_auth = AuthUser(user_id=self.u3.user_id)
173 perms = {
175 perms = {
174 'repositories_groups': {},
176 'repositories_groups': {},
175 'global': set([u'hg.create.repository', u'repository.read',
177 'global': set([u'hg.create.repository', u'repository.read',
176 u'hg.register.manual_activate']),
178 u'hg.register.manual_activate']),
177 'repositories': {u'vcs_test_hg': u'repository.read'}
179 'repositories': {u'vcs_test_hg': u'repository.read'}
178 }
180 }
179 self.assertEqual(u3_auth.permissions['repositories'][HG_REPO],
181 self.assertEqual(u3_auth.permissions['repositories'][HG_REPO],
180 new_perm_gr)
182 new_perm_gr)
181 self.assertEqual(u3_auth.permissions['repositories_groups'],
183 self.assertEqual(u3_auth.permissions['repositories_groups'],
182 perms['repositories_groups'])
184 perms['repositories_groups'])
183
185
184 def test_propagated_permission_from_users_group_lower_weight(self):
186 def test_propagated_permission_from_users_group_lower_weight(self):
185 # make group
187 # make group
186 self.ug1 = UserGroupModel().create('G1')
188 self.ug1 = UserGroupModel().create('G1')
187 # add user to group
189 # add user to group
188 UserGroupModel().add_user_to_group(self.ug1, self.u1)
190 UserGroupModel().add_user_to_group(self.ug1, self.u1)
189
191
190 # set permission to lower
192 # set permission to lower
191 new_perm_h = 'repository.write'
193 new_perm_h = 'repository.write'
192 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
194 RepoModel().grant_user_permission(repo=HG_REPO, user=self.u1,
193 perm=new_perm_h)
195 perm=new_perm_h)
194 Session().commit()
196 Session().commit()
195 u1_auth = AuthUser(user_id=self.u1.user_id)
197 u1_auth = AuthUser(user_id=self.u1.user_id)
196 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
198 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
197 new_perm_h)
199 new_perm_h)
198
200
199 # grant perm for group this should NOT override permission from user
201 # grant perm for group this should NOT override permission from user
200 # since it's lower than granted
202 # since it's lower than granted
201 new_perm_l = 'repository.read'
203 new_perm_l = 'repository.read'
202 RepoModel().grant_users_group_permission(repo=HG_REPO,
204 RepoModel().grant_users_group_permission(repo=HG_REPO,
203 group_name=self.ug1,
205 group_name=self.ug1,
204 perm=new_perm_l)
206 perm=new_perm_l)
205 # check perms
207 # check perms
206 u1_auth = AuthUser(user_id=self.u1.user_id)
208 u1_auth = AuthUser(user_id=self.u1.user_id)
207 perms = {
209 perms = {
208 'repositories_groups': {},
210 'repositories_groups': {},
209 'global': set([u'hg.create.repository', u'repository.read',
211 'global': set([u'hg.create.repository', u'repository.read',
210 u'hg.register.manual_activate']),
212 u'hg.register.manual_activate']),
211 'repositories': {u'vcs_test_hg': u'repository.write'}
213 'repositories': {u'vcs_test_hg': u'repository.write'}
212 }
214 }
213 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
215 self.assertEqual(u1_auth.permissions['repositories'][HG_REPO],
214 new_perm_h)
216 new_perm_h)
215 self.assertEqual(u1_auth.permissions['repositories_groups'],
217 self.assertEqual(u1_auth.permissions['repositories_groups'],
216 perms['repositories_groups'])
218 perms['repositories_groups'])
217
219
218 def test_repo_in_group_permissions(self):
220 def test_repo_in_group_permissions(self):
219 self.g1 = _make_group('group1', skip_if_exists=True)
221 self.g1 = fixture.create_group('group1', skip_if_exists=True)
220 self.g2 = _make_group('group2', skip_if_exists=True)
222 self.g2 = fixture.create_group('group2', skip_if_exists=True)
221 Session().commit()
222 # both perms should be read !
223 # both perms should be read !
223 u1_auth = AuthUser(user_id=self.u1.user_id)
224 u1_auth = AuthUser(user_id=self.u1.user_id)
224 self.assertEqual(u1_auth.permissions['repositories_groups'],
225 self.assertEqual(u1_auth.permissions['repositories_groups'],
225 {u'group1': u'group.read', u'group2': u'group.read'})
226 {u'group1': u'group.read', u'group2': u'group.read'})
226
227
227 a1_auth = AuthUser(user_id=self.anon.user_id)
228 a1_auth = AuthUser(user_id=self.anon.user_id)
228 self.assertEqual(a1_auth.permissions['repositories_groups'],
229 self.assertEqual(a1_auth.permissions['repositories_groups'],
229 {u'group1': u'group.read', u'group2': u'group.read'})
230 {u'group1': u'group.read', u'group2': u'group.read'})
230
231
231 #Change perms to none for both groups
232 #Change perms to none for both groups
232 ReposGroupModel().grant_user_permission(repos_group=self.g1,
233 ReposGroupModel().grant_user_permission(repos_group=self.g1,
233 user=self.anon,
234 user=self.anon,
234 perm='group.none')
235 perm='group.none')
235 ReposGroupModel().grant_user_permission(repos_group=self.g2,
236 ReposGroupModel().grant_user_permission(repos_group=self.g2,
236 user=self.anon,
237 user=self.anon,
237 perm='group.none')
238 perm='group.none')
238
239
239 u1_auth = AuthUser(user_id=self.u1.user_id)
240 u1_auth = AuthUser(user_id=self.u1.user_id)
240 self.assertEqual(u1_auth.permissions['repositories_groups'],
241 self.assertEqual(u1_auth.permissions['repositories_groups'],
241 {u'group1': u'group.none', u'group2': u'group.none'})
242 {u'group1': u'group.none', u'group2': u'group.none'})
242
243
243 a1_auth = AuthUser(user_id=self.anon.user_id)
244 a1_auth = AuthUser(user_id=self.anon.user_id)
244 self.assertEqual(a1_auth.permissions['repositories_groups'],
245 self.assertEqual(a1_auth.permissions['repositories_groups'],
245 {u'group1': u'group.none', u'group2': u'group.none'})
246 {u'group1': u'group.none', u'group2': u'group.none'})
246
247
247 # add repo to group
248 # add repo to group
248 name = RepoGroup.url_sep().join([self.g1.group_name, 'test_perm'])
249 name = RepoGroup.url_sep().join([self.g1.group_name, 'test_perm'])
249 self.test_repo = RepoModel().create_repo(
250 self.test_repo = fixture.create_repo(name=name,
250 repo_name=name,
251 repo_type='hg',
251 repo_type='hg',
252 repos_group=self.g1,
252 description='',
253 cur_user=self.u1,)
253 repos_group=self.g1,
254 owner=self.u1,
255 )
256 Session().commit()
257
254
258 u1_auth = AuthUser(user_id=self.u1.user_id)
255 u1_auth = AuthUser(user_id=self.u1.user_id)
259 self.assertEqual(u1_auth.permissions['repositories_groups'],
256 self.assertEqual(u1_auth.permissions['repositories_groups'],
260 {u'group1': u'group.none', u'group2': u'group.none'})
257 {u'group1': u'group.none', u'group2': u'group.none'})
261
258
262 a1_auth = AuthUser(user_id=self.anon.user_id)
259 a1_auth = AuthUser(user_id=self.anon.user_id)
263 self.assertEqual(a1_auth.permissions['repositories_groups'],
260 self.assertEqual(a1_auth.permissions['repositories_groups'],
264 {u'group1': u'group.none', u'group2': u'group.none'})
261 {u'group1': u'group.none', u'group2': u'group.none'})
265
262
266 #grant permission for u2 !
263 #grant permission for u2 !
267 ReposGroupModel().grant_user_permission(repos_group=self.g1,
264 ReposGroupModel().grant_user_permission(repos_group=self.g1,
268 user=self.u2,
265 user=self.u2,
269 perm='group.read')
266 perm='group.read')
270 ReposGroupModel().grant_user_permission(repos_group=self.g2,
267 ReposGroupModel().grant_user_permission(repos_group=self.g2,
271 user=self.u2,
268 user=self.u2,
272 perm='group.read')
269 perm='group.read')
273 Session().commit()
270 Session().commit()
274 self.assertNotEqual(self.u1, self.u2)
271 self.assertNotEqual(self.u1, self.u2)
275 #u1 and anon should have not change perms while u2 should !
272 #u1 and anon should have not change perms while u2 should !
276 u1_auth = AuthUser(user_id=self.u1.user_id)
273 u1_auth = AuthUser(user_id=self.u1.user_id)
277 self.assertEqual(u1_auth.permissions['repositories_groups'],
274 self.assertEqual(u1_auth.permissions['repositories_groups'],
278 {u'group1': u'group.none', u'group2': u'group.none'})
275 {u'group1': u'group.none', u'group2': u'group.none'})
279
276
280 u2_auth = AuthUser(user_id=self.u2.user_id)
277 u2_auth = AuthUser(user_id=self.u2.user_id)
281 self.assertEqual(u2_auth.permissions['repositories_groups'],
278 self.assertEqual(u2_auth.permissions['repositories_groups'],
282 {u'group1': u'group.read', u'group2': u'group.read'})
279 {u'group1': u'group.read', u'group2': u'group.read'})
283
280
284 a1_auth = AuthUser(user_id=self.anon.user_id)
281 a1_auth = AuthUser(user_id=self.anon.user_id)
285 self.assertEqual(a1_auth.permissions['repositories_groups'],
282 self.assertEqual(a1_auth.permissions['repositories_groups'],
286 {u'group1': u'group.none', u'group2': u'group.none'})
283 {u'group1': u'group.none', u'group2': u'group.none'})
287
284
288 def test_repo_group_user_as_user_group_member(self):
285 def test_repo_group_user_as_user_group_member(self):
289 # create Group1
286 # create Group1
290 self.g1 = _make_group('group1', skip_if_exists=True)
287 self.g1 = fixture.create_group('group1', skip_if_exists=True)
291 Session().commit()
292 a1_auth = AuthUser(user_id=self.anon.user_id)
288 a1_auth = AuthUser(user_id=self.anon.user_id)
293
289
294 self.assertEqual(a1_auth.permissions['repositories_groups'],
290 self.assertEqual(a1_auth.permissions['repositories_groups'],
295 {u'group1': u'group.read'})
291 {u'group1': u'group.read'})
296
292
297 # set default permission to none
293 # set default permission to none
298 ReposGroupModel().grant_user_permission(repos_group=self.g1,
294 ReposGroupModel().grant_user_permission(repos_group=self.g1,
299 user=self.anon,
295 user=self.anon,
300 perm='group.none')
296 perm='group.none')
301 # make group
297 # make group
302 self.ug1 = UserGroupModel().create('G1')
298 self.ug1 = UserGroupModel().create('G1')
303 # add user to group
299 # add user to group
304 UserGroupModel().add_user_to_group(self.ug1, self.u1)
300 UserGroupModel().add_user_to_group(self.ug1, self.u1)
305 Session().commit()
301 Session().commit()
306
302
307 # check if user is in the group
303 # check if user is in the group
308 membrs = [x.user_id for x in UserGroupModel().get(self.ug1.users_group_id).members]
304 membrs = [x.user_id for x in UserGroupModel().get(self.ug1.users_group_id).members]
309 self.assertEqual(membrs, [self.u1.user_id])
305 self.assertEqual(membrs, [self.u1.user_id])
310 # add some user to that group
306 # add some user to that group
311
307
312 # check his permissions
308 # check his permissions
313 a1_auth = AuthUser(user_id=self.anon.user_id)
309 a1_auth = AuthUser(user_id=self.anon.user_id)
314 self.assertEqual(a1_auth.permissions['repositories_groups'],
310 self.assertEqual(a1_auth.permissions['repositories_groups'],
315 {u'group1': u'group.none'})
311 {u'group1': u'group.none'})
316
312
317 u1_auth = AuthUser(user_id=self.u1.user_id)
313 u1_auth = AuthUser(user_id=self.u1.user_id)
318 self.assertEqual(u1_auth.permissions['repositories_groups'],
314 self.assertEqual(u1_auth.permissions['repositories_groups'],
319 {u'group1': u'group.none'})
315 {u'group1': u'group.none'})
320
316
321 # grant ug1 read permissions for
317 # grant ug1 read permissions for
322 ReposGroupModel().grant_users_group_permission(repos_group=self.g1,
318 ReposGroupModel().grant_users_group_permission(repos_group=self.g1,
323 group_name=self.ug1,
319 group_name=self.ug1,
324 perm='group.read')
320 perm='group.read')
325 Session().commit()
321 Session().commit()
326 # check if the
322 # check if the
327 obj = Session().query(UserGroupRepoGroupToPerm)\
323 obj = Session().query(UserGroupRepoGroupToPerm)\
328 .filter(UserGroupRepoGroupToPerm.group == self.g1)\
324 .filter(UserGroupRepoGroupToPerm.group == self.g1)\
329 .filter(UserGroupRepoGroupToPerm.users_group == self.ug1)\
325 .filter(UserGroupRepoGroupToPerm.users_group == self.ug1)\
330 .scalar()
326 .scalar()
331 self.assertEqual(obj.permission.permission_name, 'group.read')
327 self.assertEqual(obj.permission.permission_name, 'group.read')
332
328
333 a1_auth = AuthUser(user_id=self.anon.user_id)
329 a1_auth = AuthUser(user_id=self.anon.user_id)
334
330
335 self.assertEqual(a1_auth.permissions['repositories_groups'],
331 self.assertEqual(a1_auth.permissions['repositories_groups'],
336 {u'group1': u'group.none'})
332 {u'group1': u'group.none'})
337
333
338 u1_auth = AuthUser(user_id=self.u1.user_id)
334 u1_auth = AuthUser(user_id=self.u1.user_id)
339 self.assertEqual(u1_auth.permissions['repositories_groups'],
335 self.assertEqual(u1_auth.permissions['repositories_groups'],
340 {u'group1': u'group.read'})
336 {u'group1': u'group.read'})
341
337
342 def test_inherited_permissions_from_default_on_user_enabled(self):
338 def test_inherited_permissions_from_default_on_user_enabled(self):
343 user_model = UserModel()
339 user_model = UserModel()
344 # enable fork and create on default user
340 # enable fork and create on default user
345 usr = 'default'
341 usr = 'default'
346 user_model.revoke_perm(usr, 'hg.create.none')
342 user_model.revoke_perm(usr, 'hg.create.none')
347 user_model.grant_perm(usr, 'hg.create.repository')
343 user_model.grant_perm(usr, 'hg.create.repository')
348 user_model.revoke_perm(usr, 'hg.fork.none')
344 user_model.revoke_perm(usr, 'hg.fork.none')
349 user_model.grant_perm(usr, 'hg.fork.repository')
345 user_model.grant_perm(usr, 'hg.fork.repository')
350 # make sure inherit flag is turned on
346 # make sure inherit flag is turned on
351 self.u1.inherit_default_permissions = True
347 self.u1.inherit_default_permissions = True
352 Session().commit()
348 Session().commit()
353 u1_auth = AuthUser(user_id=self.u1.user_id)
349 u1_auth = AuthUser(user_id=self.u1.user_id)
354 # this user will have inherited permissions from default user
350 # this user will have inherited permissions from default user
355 self.assertEqual(u1_auth.permissions['global'],
351 self.assertEqual(u1_auth.permissions['global'],
356 set(['hg.create.repository', 'hg.fork.repository',
352 set(['hg.create.repository', 'hg.fork.repository',
357 'hg.register.manual_activate',
353 'hg.register.manual_activate',
358 'repository.read', 'group.read']))
354 'repository.read', 'group.read']))
359
355
360 def test_inherited_permissions_from_default_on_user_disabled(self):
356 def test_inherited_permissions_from_default_on_user_disabled(self):
361 user_model = UserModel()
357 user_model = UserModel()
362 # disable fork and create on default user
358 # disable fork and create on default user
363 usr = 'default'
359 usr = 'default'
364 user_model.revoke_perm(usr, 'hg.create.repository')
360 user_model.revoke_perm(usr, 'hg.create.repository')
365 user_model.grant_perm(usr, 'hg.create.none')
361 user_model.grant_perm(usr, 'hg.create.none')
366 user_model.revoke_perm(usr, 'hg.fork.repository')
362 user_model.revoke_perm(usr, 'hg.fork.repository')
367 user_model.grant_perm(usr, 'hg.fork.none')
363 user_model.grant_perm(usr, 'hg.fork.none')
368 # make sure inherit flag is turned on
364 # make sure inherit flag is turned on
369 self.u1.inherit_default_permissions = True
365 self.u1.inherit_default_permissions = True
370 Session().commit()
366 Session().commit()
371 u1_auth = AuthUser(user_id=self.u1.user_id)
367 u1_auth = AuthUser(user_id=self.u1.user_id)
372 # this user will have inherited permissions from default user
368 # this user will have inherited permissions from default user
373 self.assertEqual(u1_auth.permissions['global'],
369 self.assertEqual(u1_auth.permissions['global'],
374 set(['hg.create.none', 'hg.fork.none',
370 set(['hg.create.none', 'hg.fork.none',
375 'hg.register.manual_activate',
371 'hg.register.manual_activate',
376 'repository.read', 'group.read']))
372 'repository.read', 'group.read']))
377
373
378 def test_non_inherited_permissions_from_default_on_user_enabled(self):
374 def test_non_inherited_permissions_from_default_on_user_enabled(self):
379 user_model = UserModel()
375 user_model = UserModel()
380 # enable fork and create on default user
376 # enable fork and create on default user
381 usr = 'default'
377 usr = 'default'
382 user_model.revoke_perm(usr, 'hg.create.none')
378 user_model.revoke_perm(usr, 'hg.create.none')
383 user_model.grant_perm(usr, 'hg.create.repository')
379 user_model.grant_perm(usr, 'hg.create.repository')
384 user_model.revoke_perm(usr, 'hg.fork.none')
380 user_model.revoke_perm(usr, 'hg.fork.none')
385 user_model.grant_perm(usr, 'hg.fork.repository')
381 user_model.grant_perm(usr, 'hg.fork.repository')
386
382
387 #disable global perms on specific user
383 #disable global perms on specific user
388 user_model.revoke_perm(self.u1, 'hg.create.repository')
384 user_model.revoke_perm(self.u1, 'hg.create.repository')
389 user_model.grant_perm(self.u1, 'hg.create.none')
385 user_model.grant_perm(self.u1, 'hg.create.none')
390 user_model.revoke_perm(self.u1, 'hg.fork.repository')
386 user_model.revoke_perm(self.u1, 'hg.fork.repository')
391 user_model.grant_perm(self.u1, 'hg.fork.none')
387 user_model.grant_perm(self.u1, 'hg.fork.none')
392
388
393 # make sure inherit flag is turned off
389 # make sure inherit flag is turned off
394 self.u1.inherit_default_permissions = False
390 self.u1.inherit_default_permissions = False
395 Session().commit()
391 Session().commit()
396 u1_auth = AuthUser(user_id=self.u1.user_id)
392 u1_auth = AuthUser(user_id=self.u1.user_id)
397 # this user will have non inherited permissions from he's
393 # this user will have non inherited permissions from he's
398 # explicitly set permissions
394 # explicitly set permissions
399 self.assertEqual(u1_auth.permissions['global'],
395 self.assertEqual(u1_auth.permissions['global'],
400 set(['hg.create.none', 'hg.fork.none',
396 set(['hg.create.none', 'hg.fork.none',
401 'hg.register.manual_activate',
397 'hg.register.manual_activate',
402 'repository.read', 'group.read']))
398 'repository.read', 'group.read']))
403
399
404 def test_non_inherited_permissions_from_default_on_user_disabled(self):
400 def test_non_inherited_permissions_from_default_on_user_disabled(self):
405 user_model = UserModel()
401 user_model = UserModel()
406 # disable fork and create on default user
402 # disable fork and create on default user
407 usr = 'default'
403 usr = 'default'
408 user_model.revoke_perm(usr, 'hg.create.repository')
404 user_model.revoke_perm(usr, 'hg.create.repository')
409 user_model.grant_perm(usr, 'hg.create.none')
405 user_model.grant_perm(usr, 'hg.create.none')
410 user_model.revoke_perm(usr, 'hg.fork.repository')
406 user_model.revoke_perm(usr, 'hg.fork.repository')
411 user_model.grant_perm(usr, 'hg.fork.none')
407 user_model.grant_perm(usr, 'hg.fork.none')
412
408
413 #enable global perms on specific user
409 #enable global perms on specific user
414 user_model.revoke_perm(self.u1, 'hg.create.none')
410 user_model.revoke_perm(self.u1, 'hg.create.none')
415 user_model.grant_perm(self.u1, 'hg.create.repository')
411 user_model.grant_perm(self.u1, 'hg.create.repository')
416 user_model.revoke_perm(self.u1, 'hg.fork.none')
412 user_model.revoke_perm(self.u1, 'hg.fork.none')
417 user_model.grant_perm(self.u1, 'hg.fork.repository')
413 user_model.grant_perm(self.u1, 'hg.fork.repository')
418
414
419 # make sure inherit flag is turned off
415 # make sure inherit flag is turned off
420 self.u1.inherit_default_permissions = False
416 self.u1.inherit_default_permissions = False
421 Session().commit()
417 Session().commit()
422 u1_auth = AuthUser(user_id=self.u1.user_id)
418 u1_auth = AuthUser(user_id=self.u1.user_id)
423 # this user will have non inherited permissions from he's
419 # this user will have non inherited permissions from he's
424 # explicitly set permissions
420 # explicitly set permissions
425 self.assertEqual(u1_auth.permissions['global'],
421 self.assertEqual(u1_auth.permissions['global'],
426 set(['hg.create.repository', 'hg.fork.repository',
422 set(['hg.create.repository', 'hg.fork.repository',
427 'hg.register.manual_activate',
423 'hg.register.manual_activate',
428 'repository.read', 'group.read']))
424 'repository.read', 'group.read']))
429
425
430 def test_owner_permissions_doesnot_get_overwritten_by_group(self):
426 def test_owner_permissions_doesnot_get_overwritten_by_group(self):
431 #create repo as USER,
427 #create repo as USER,
432 self.test_repo = repo = RepoModel().create_repo(repo_name='myownrepo',
428 self.test_repo = fixture.create_repo(name='myownrepo',
433 repo_type='hg',
429 repo_type='hg',
434 description='desc',
430 cur_user=self.u1)
435 owner=self.u1)
436
431
437 Session().commit()
438 #he has permissions of admin as owner
432 #he has permissions of admin as owner
439 u1_auth = AuthUser(user_id=self.u1.user_id)
433 u1_auth = AuthUser(user_id=self.u1.user_id)
440 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
434 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
441 'repository.admin')
435 'repository.admin')
442 #set his permission as user group, he should still be admin
436 #set his permission as user group, he should still be admin
443 self.ug1 = UserGroupModel().create('G1')
437 self.ug1 = UserGroupModel().create('G1')
444 # add user to group
438 # add user to group
445 UserGroupModel().add_user_to_group(self.ug1, self.u1)
439 UserGroupModel().add_user_to_group(self.ug1, self.u1)
446 RepoModel().grant_users_group_permission(repo, group_name=self.ug1,
440 RepoModel().grant_users_group_permission(self.test_repo,
441 group_name=self.ug1,
447 perm='repository.none')
442 perm='repository.none')
448
443
449 Session().commit()
444 Session().commit()
450 u1_auth = AuthUser(user_id=self.u1.user_id)
445 u1_auth = AuthUser(user_id=self.u1.user_id)
451 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
446 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
452 'repository.admin')
447 'repository.admin')
453
448
454 def test_owner_permissions_doesnot_get_overwritten_by_others(self):
449 def test_owner_permissions_doesnot_get_overwritten_by_others(self):
455 #create repo as USER,
450 #create repo as USER,
456 self.test_repo = repo = RepoModel().create_repo(repo_name='myownrepo',
451 self.test_repo = fixture.create_repo(name='myownrepo',
457 repo_type='hg',
452 repo_type='hg',
458 description='desc',
453 cur_user=self.u1)
459 owner=self.u1)
460
454
461 Session().commit()
462 #he has permissions of admin as owner
455 #he has permissions of admin as owner
463 u1_auth = AuthUser(user_id=self.u1.user_id)
456 u1_auth = AuthUser(user_id=self.u1.user_id)
464 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
457 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
465 'repository.admin')
458 'repository.admin')
466 #set his permission as user, he should still be admin
459 #set his permission as user, he should still be admin
467 RepoModel().grant_user_permission(repo, user=self.u1,
460 RepoModel().grant_user_permission(self.test_repo, user=self.u1,
468 perm='repository.none')
461 perm='repository.none')
469 Session().commit()
462 Session().commit()
470 u1_auth = AuthUser(user_id=self.u1.user_id)
463 u1_auth = AuthUser(user_id=self.u1.user_id)
471 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
464 self.assertEqual(u1_auth.permissions['repositories']['myownrepo'],
472 'repository.admin')
465 'repository.admin')
@@ -1,242 +1,200 b''
1 import os
1 import os
2 import unittest
2 import unittest
3 from sqlalchemy.exc import IntegrityError
4
3 from rhodecode.tests import *
5 from rhodecode.tests import *
6 from rhodecode.tests.fixture import Fixture
4
7
5 from rhodecode.model.repos_group import ReposGroupModel
8 from rhodecode.model.repos_group import ReposGroupModel
6 from rhodecode.model.repo import RepoModel
9 from rhodecode.model.repo import RepoModel
7 from rhodecode.model.db import RepoGroup, User
10 from rhodecode.model.db import RepoGroup
8 from rhodecode.model.meta import Session
11 from rhodecode.model.meta import Session
9 from sqlalchemy.exc import IntegrityError
10
12
11
13
12 def _make_group(path, desc='desc', parent_id=None,
14 fixture = Fixture()
13 skip_if_exists=False):
14
15 gr = RepoGroup.get_by_group_name(path)
16 if gr and skip_if_exists:
17 return gr
18 if isinstance(parent_id, RepoGroup):
19 parent_id = parent_id.group_id
20 gr = ReposGroupModel().create(path, desc, TEST_USER_ADMIN_LOGIN, parent_id)
21 return gr
22
15
23
16
24 def _update_group(id_, group_name, desc='desc', parent_id=None):
17 def _update_group(id_, group_name, desc='desc', parent_id=None):
25 form_data = _get_group_create_params(group_name=group_name,
18 form_data = fixture._get_group_create_params(group_name=group_name,
26 group_desc=desc,
19 group_desc=desc,
27 group_parent_id=parent_id)
20 group_parent_id=parent_id)
28 gr = ReposGroupModel().update(id_, form_data)
21 gr = ReposGroupModel().update(id_, form_data)
29 return gr
22 return gr
30
23
31
24
32 def _make_repo(name, **kwargs):
33 form_data = _get_repo_create_params(repo_name=name, **kwargs)
34 cur_user = User.get_by_username(TEST_USER_ADMIN_LOGIN)
35 r = RepoModel().create(form_data, cur_user)
36 return r
37
38
39 def _update_repo(name, **kwargs):
25 def _update_repo(name, **kwargs):
40 form_data = _get_repo_create_params(**kwargs)
26 form_data = fixture._get_repo_create_params(**kwargs)
41 if not 'repo_name' in kwargs:
27 if not 'repo_name' in kwargs:
42 form_data['repo_name'] = name
28 form_data['repo_name'] = name
43 if not 'perms_new' in kwargs:
29 if not 'perms_new' in kwargs:
44 form_data['perms_new'] = []
30 form_data['perms_new'] = []
45 if not 'perms_updates' in kwargs:
31 if not 'perms_updates' in kwargs:
46 form_data['perms_updates'] = []
32 form_data['perms_updates'] = []
47 r = RepoModel().update(name, **form_data)
33 r = RepoModel().update(name, **form_data)
48 return r
34 return r
49
35
50
36
51 class TestReposGroups(unittest.TestCase):
37 class TestReposGroups(unittest.TestCase):
52
38
53 def setUp(self):
39 def setUp(self):
54 self.g1 = _make_group('test1', skip_if_exists=True)
40 self.g1 = fixture.create_group('test1', skip_if_exists=True)
55 Session().commit()
41 self.g2 = fixture.create_group('test2', skip_if_exists=True)
56 self.g2 = _make_group('test2', skip_if_exists=True)
42 self.g3 = fixture.create_group('test3', skip_if_exists=True)
57 Session().commit()
58 self.g3 = _make_group('test3', skip_if_exists=True)
59 Session().commit()
60
43
61 def tearDown(self):
44 def tearDown(self):
62 Session.remove()
45 Session.remove()
63
46
64 def __check_path(self, *path):
47 def __check_path(self, *path):
65 """
48 """
66 Checks the path for existance !
49 Checks the path for existance !
67 """
50 """
68 path = [TESTS_TMP_PATH] + list(path)
51 path = [TESTS_TMP_PATH] + list(path)
69 path = os.path.join(*path)
52 path = os.path.join(*path)
70 return os.path.isdir(path)
53 return os.path.isdir(path)
71
54
72 def _check_folders(self):
55 def _check_folders(self):
73 print os.listdir(TESTS_TMP_PATH)
56 print os.listdir(TESTS_TMP_PATH)
74
57
75 def __delete_group(self, id_):
58 def __delete_group(self, id_):
76 ReposGroupModel().delete(id_)
59 ReposGroupModel().delete(id_)
77
60
78 def test_create_group(self):
61 def test_create_group(self):
79 g = _make_group('newGroup')
62 g = fixture.create_group('newGroup')
80 Session().commit()
63 Session().commit()
81 self.assertEqual(g.full_path, 'newGroup')
64 self.assertEqual(g.full_path, 'newGroup')
82
65
83 self.assertTrue(self.__check_path('newGroup'))
66 self.assertTrue(self.__check_path('newGroup'))
84
67
85 def test_create_same_name_group(self):
68 def test_create_same_name_group(self):
86 self.assertRaises(IntegrityError, lambda: _make_group('newGroup'))
69 self.assertRaises(IntegrityError, lambda: fixture.create_group('newGroup'))
87 Session().rollback()
70 Session().rollback()
88
71
89 def test_same_subgroup(self):
72 def test_same_subgroup(self):
90 sg1 = _make_group('sub1', parent_id=self.g1.group_id)
73 sg1 = fixture.create_group('sub1', group_parent_id=self.g1.group_id)
91 Session().commit()
92 self.assertEqual(sg1.parent_group, self.g1)
74 self.assertEqual(sg1.parent_group, self.g1)
93 self.assertEqual(sg1.full_path, 'test1/sub1')
75 self.assertEqual(sg1.full_path, 'test1/sub1')
94 self.assertTrue(self.__check_path('test1', 'sub1'))
76 self.assertTrue(self.__check_path('test1', 'sub1'))
95
77
96 ssg1 = _make_group('subsub1', parent_id=sg1.group_id)
78 ssg1 = fixture.create_group('subsub1', group_parent_id=sg1.group_id)
97 Session().commit()
98 self.assertEqual(ssg1.parent_group, sg1)
79 self.assertEqual(ssg1.parent_group, sg1)
99 self.assertEqual(ssg1.full_path, 'test1/sub1/subsub1')
80 self.assertEqual(ssg1.full_path, 'test1/sub1/subsub1')
100 self.assertTrue(self.__check_path('test1', 'sub1', 'subsub1'))
81 self.assertTrue(self.__check_path('test1', 'sub1', 'subsub1'))
101
82
102 def test_remove_group(self):
83 def test_remove_group(self):
103 sg1 = _make_group('deleteme')
84 sg1 = fixture.create_group('deleteme')
104 Session().commit()
105 self.__delete_group(sg1.group_id)
85 self.__delete_group(sg1.group_id)
106
86
107 self.assertEqual(RepoGroup.get(sg1.group_id), None)
87 self.assertEqual(RepoGroup.get(sg1.group_id), None)
108 self.assertFalse(self.__check_path('deteteme'))
88 self.assertFalse(self.__check_path('deteteme'))
109
89
110 sg1 = _make_group('deleteme', parent_id=self.g1.group_id)
90 sg1 = fixture.create_group('deleteme', group_parent_id=self.g1.group_id)
111 Session().commit()
112 self.__delete_group(sg1.group_id)
91 self.__delete_group(sg1.group_id)
113
92
114 self.assertEqual(RepoGroup.get(sg1.group_id), None)
93 self.assertEqual(RepoGroup.get(sg1.group_id), None)
115 self.assertFalse(self.__check_path('test1', 'deteteme'))
94 self.assertFalse(self.__check_path('test1', 'deteteme'))
116
95
117 def test_rename_single_group(self):
96 def test_rename_single_group(self):
118 sg1 = _make_group('initial')
97 sg1 = fixture.create_group('initial')
119 Session().commit()
120
98
121 new_sg1 = _update_group(sg1.group_id, 'after')
99 new_sg1 = _update_group(sg1.group_id, 'after')
122 self.assertTrue(self.__check_path('after'))
100 self.assertTrue(self.__check_path('after'))
123 self.assertEqual(RepoGroup.get_by_group_name('initial'), None)
101 self.assertEqual(RepoGroup.get_by_group_name('initial'), None)
124
102
125 def test_update_group_parent(self):
103 def test_update_group_parent(self):
126
104
127 sg1 = _make_group('initial', parent_id=self.g1.group_id)
105 sg1 = fixture.create_group('initial', group_parent_id=self.g1.group_id)
128 Session().commit()
129
106
130 new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
107 new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g1.group_id)
131 self.assertTrue(self.__check_path('test1', 'after'))
108 self.assertTrue(self.__check_path('test1', 'after'))
132 self.assertEqual(RepoGroup.get_by_group_name('test1/initial'), None)
109 self.assertEqual(RepoGroup.get_by_group_name('test1/initial'), None)
133
110
134 new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
111 new_sg1 = _update_group(sg1.group_id, 'after', parent_id=self.g3.group_id)
135 self.assertTrue(self.__check_path('test3', 'after'))
112 self.assertTrue(self.__check_path('test3', 'after'))
136 self.assertEqual(RepoGroup.get_by_group_name('test3/initial'), None)
113 self.assertEqual(RepoGroup.get_by_group_name('test3/initial'), None)
137
114
138 new_sg1 = _update_group(sg1.group_id, 'hello')
115 new_sg1 = _update_group(sg1.group_id, 'hello')
139 self.assertTrue(self.__check_path('hello'))
116 self.assertTrue(self.__check_path('hello'))
140
117
141 self.assertEqual(RepoGroup.get_by_group_name('hello'), new_sg1)
118 self.assertEqual(RepoGroup.get_by_group_name('hello'), new_sg1)
142
119
143 def test_subgrouping_with_repo(self):
120 def test_subgrouping_with_repo(self):
144
121
145 g1 = _make_group('g1')
122 g1 = fixture.create_group('g1')
146 g2 = _make_group('g2')
123 g2 = fixture.create_group('g2')
147 Session().commit()
148 # create new repo
124 # create new repo
149 r = _make_repo('john')
125 r = fixture.create_repo('john')
150 Session().commit()
126
151 self.assertEqual(r.repo_name, 'john')
127 self.assertEqual(r.repo_name, 'john')
152 # put repo into group
128 # put repo into group
153 r = _update_repo('john', repo_group=g1.group_id)
129 r = _update_repo('john', repo_group=g1.group_id)
154 Session().commit()
130 Session().commit()
155 self.assertEqual(r.repo_name, 'g1/john')
131 self.assertEqual(r.repo_name, 'g1/john')
156
132
157 _update_group(g1.group_id, 'g1', parent_id=g2.group_id)
133 _update_group(g1.group_id, 'g1', parent_id=g2.group_id)
158 self.assertTrue(self.__check_path('g2', 'g1'))
134 self.assertTrue(self.__check_path('g2', 'g1'))
159
135
160 # test repo
136 # test repo
161 self.assertEqual(r.repo_name, RepoGroup.url_sep().join(['g2', 'g1',
137 self.assertEqual(r.repo_name, RepoGroup.url_sep().join(['g2', 'g1',
162 r.just_name]))
138 r.just_name]))
163
139
164 def test_move_to_root(self):
140 def test_move_to_root(self):
165 g1 = _make_group('t11')
141 g1 = fixture.create_group('t11')
166 Session().commit()
142 g2 = fixture.create_group('t22', group_parent_id=g1.group_id)
167 g2 = _make_group('t22', parent_id=g1.group_id)
168 Session().commit()
169
143
170 self.assertEqual(g2.full_path, 't11/t22')
144 self.assertEqual(g2.full_path, 't11/t22')
171 self.assertTrue(self.__check_path('t11', 't22'))
145 self.assertTrue(self.__check_path('t11', 't22'))
172
146
173 g2 = _update_group(g2.group_id, 'g22', parent_id=None)
147 g2 = _update_group(g2.group_id, 'g22', parent_id=None)
174 Session().commit()
148 Session().commit()
175
149
176 self.assertEqual(g2.group_name, 'g22')
150 self.assertEqual(g2.group_name, 'g22')
177 # we moved out group from t1 to '' so it's full path should be 'g2'
151 # we moved out group from t1 to '' so it's full path should be 'g2'
178 self.assertEqual(g2.full_path, 'g22')
152 self.assertEqual(g2.full_path, 'g22')
179 self.assertFalse(self.__check_path('t11', 't22'))
153 self.assertFalse(self.__check_path('t11', 't22'))
180 self.assertTrue(self.__check_path('g22'))
154 self.assertTrue(self.__check_path('g22'))
181
155
182 def test_rename_top_level_group_in_nested_setup(self):
156 def test_rename_top_level_group_in_nested_setup(self):
183 g1 = _make_group('L1')
157 g1 = fixture.create_group('L1')
184 Session().commit()
158 g2 = fixture.create_group('L2', group_parent_id=g1.group_id)
185 g2 = _make_group('L2', parent_id=g1.group_id)
159 g3 = fixture.create_group('L3', group_parent_id=g2.group_id)
186 Session().commit()
187 g3 = _make_group('L3', parent_id=g2.group_id)
188 Session().commit()
189
160
190 r = _make_repo('L1/L2/L3/L3_REPO', repo_group=g3.group_id)
161 r = fixture.create_repo('L1/L2/L3/L3_REPO', repo_group=g3.group_id)
191 Session().commit()
192
162
193 ##rename L1 all groups should be now changed
163 ##rename L1 all groups should be now changed
194 _update_group(g1.group_id, 'L1_NEW')
164 _update_group(g1.group_id, 'L1_NEW')
195 Session().commit()
165 Session().commit()
196 self.assertEqual(g1.full_path, 'L1_NEW')
166 self.assertEqual(g1.full_path, 'L1_NEW')
197 self.assertEqual(g2.full_path, 'L1_NEW/L2')
167 self.assertEqual(g2.full_path, 'L1_NEW/L2')
198 self.assertEqual(g3.full_path, 'L1_NEW/L2/L3')
168 self.assertEqual(g3.full_path, 'L1_NEW/L2/L3')
199 self.assertEqual(r.repo_name, 'L1_NEW/L2/L3/L3_REPO')
169 self.assertEqual(r.repo_name, 'L1_NEW/L2/L3/L3_REPO')
200
170
201 def test_change_parent_of_top_level_group_in_nested_setup(self):
171 def test_change_parent_of_top_level_group_in_nested_setup(self):
202 g1 = _make_group('R1')
172 g1 = fixture.create_group('R1')
203 Session().commit()
173 g2 = fixture.create_group('R2', group_parent_id=g1.group_id)
204 g2 = _make_group('R2', parent_id=g1.group_id)
174 g3 = fixture.create_group('R3', group_parent_id=g2.group_id)
205 Session().commit()
175 g4 = fixture.create_group('R1_NEW')
206 g3 = _make_group('R3', parent_id=g2.group_id)
207 Session().commit()
208
176
209 g4 = _make_group('R1_NEW')
177 r = fixture.create_repo('R1/R2/R3/R3_REPO', repo_group=g3.group_id)
210 Session().commit()
211
212 r = _make_repo('R1/R2/R3/R3_REPO', repo_group=g3.group_id)
213 Session().commit()
214 ##rename L1 all groups should be now changed
178 ##rename L1 all groups should be now changed
215 _update_group(g1.group_id, 'R1', parent_id=g4.group_id)
179 _update_group(g1.group_id, 'R1', parent_id=g4.group_id)
216 Session().commit()
180 Session().commit()
217 self.assertEqual(g1.full_path, 'R1_NEW/R1')
181 self.assertEqual(g1.full_path, 'R1_NEW/R1')
218 self.assertEqual(g2.full_path, 'R1_NEW/R1/R2')
182 self.assertEqual(g2.full_path, 'R1_NEW/R1/R2')
219 self.assertEqual(g3.full_path, 'R1_NEW/R1/R2/R3')
183 self.assertEqual(g3.full_path, 'R1_NEW/R1/R2/R3')
220 self.assertEqual(r.repo_name, 'R1_NEW/R1/R2/R3/R3_REPO')
184 self.assertEqual(r.repo_name, 'R1_NEW/R1/R2/R3/R3_REPO')
221
185
222 def test_change_parent_of_top_level_group_in_nested_setup_with_rename(self):
186 def test_change_parent_of_top_level_group_in_nested_setup_with_rename(self):
223 g1 = _make_group('X1')
187 g1 = fixture.create_group('X1')
224 Session().commit()
188 g2 = fixture.create_group('X2', group_parent_id=g1.group_id)
225 g2 = _make_group('X2', parent_id=g1.group_id)
189 g3 = fixture.create_group('X3', group_parent_id=g2.group_id)
226 Session().commit()
190 g4 = fixture.create_group('X1_NEW')
227 g3 = _make_group('X3', parent_id=g2.group_id)
228 Session().commit()
229
191
230 g4 = _make_group('X1_NEW')
192 r = fixture.create_repo('X1/X2/X3/X3_REPO', repo_group=g3.group_id)
231 Session().commit()
232
233 r = _make_repo('X1/X2/X3/X3_REPO', repo_group=g3.group_id)
234 Session().commit()
235
193
236 ##rename L1 all groups should be now changed
194 ##rename L1 all groups should be now changed
237 _update_group(g1.group_id, 'X1_PRIM', parent_id=g4.group_id)
195 _update_group(g1.group_id, 'X1_PRIM', parent_id=g4.group_id)
238 Session().commit()
196 Session().commit()
239 self.assertEqual(g1.full_path, 'X1_NEW/X1_PRIM')
197 self.assertEqual(g1.full_path, 'X1_NEW/X1_PRIM')
240 self.assertEqual(g2.full_path, 'X1_NEW/X1_PRIM/X2')
198 self.assertEqual(g2.full_path, 'X1_NEW/X1_PRIM/X2')
241 self.assertEqual(g3.full_path, 'X1_NEW/X1_PRIM/X2/X3')
199 self.assertEqual(g3.full_path, 'X1_NEW/X1_PRIM/X2/X3')
242 self.assertEqual(r.repo_name, 'X1_NEW/X1_PRIM/X2/X3/X3_REPO')
200 self.assertEqual(r.repo_name, 'X1_NEW/X1_PRIM/X2/X3/X3_REPO')
@@ -1,124 +1,128 b''
1 import unittest
1 import unittest
2 from rhodecode.tests import *
2 from rhodecode.tests import *
3
3
4 from rhodecode.model.db import User, UserGroup, UserGroupMember, UserEmailMap,\
4 from rhodecode.model.db import User, UserGroup, UserGroupMember, UserEmailMap,\
5 Permission
5 Permission
6 from rhodecode.model.user import UserModel
6 from rhodecode.model.user import UserModel
7
7
8 from rhodecode.model.meta import Session
8 from rhodecode.model.meta import Session
9 from rhodecode.model.users_group import UserGroupModel
9 from rhodecode.model.users_group import UserGroupModel
10
10
11
11
12 class TestUser(unittest.TestCase):
12 class TestUser(unittest.TestCase):
13 def __init__(self, methodName='runTest'):
13 def __init__(self, methodName='runTest'):
14 Session.remove()
14 Session.remove()
15 super(TestUser, self).__init__(methodName=methodName)
15 super(TestUser, self).__init__(methodName=methodName)
16
16
17 def tearDown(self):
18 Session.remove()
19
17 def test_create_and_remove(self):
20 def test_create_and_remove(self):
18 usr = UserModel().create_or_update(username=u'test_user',
21 usr = UserModel().create_or_update(username=u'test_user',
19 password=u'qweqwe',
22 password=u'qweqwe',
20 email=u'u232@rhodecode.org',
23 email=u'u232@rhodecode.org',
21 firstname=u'u1', lastname=u'u1')
24 firstname=u'u1', lastname=u'u1')
22 Session().commit()
25 Session().commit()
23 self.assertEqual(User.get_by_username(u'test_user'), usr)
26 self.assertEqual(User.get_by_username(u'test_user'), usr)
24
27
25 # make user group
28 # make user group
26 users_group = UserGroupModel().create('some_example_group')
29 users_group = UserGroupModel().create('some_example_group')
27 Session().commit()
30 Session().commit()
28
31
29 UserGroupModel().add_user_to_group(users_group, usr)
32 UserGroupModel().add_user_to_group(users_group, usr)
30 Session().commit()
33 Session().commit()
31
34
32 self.assertEqual(UserGroup.get(users_group.users_group_id), users_group)
35 self.assertEqual(UserGroup.get(users_group.users_group_id), users_group)
33 self.assertEqual(UserGroupMember.query().count(), 1)
36 self.assertEqual(UserGroupMember.query().count(), 1)
34 UserModel().delete(usr.user_id)
37 UserModel().delete(usr.user_id)
35 Session().commit()
38 Session().commit()
36
39
37 self.assertEqual(UserGroupMember.query().all(), [])
40 self.assertEqual(UserGroupMember.query().all(), [])
38
41
39 def test_additonal_email_as_main(self):
42 def test_additonal_email_as_main(self):
40 usr = UserModel().create_or_update(username=u'test_user',
43 usr = UserModel().create_or_update(username=u'test_user',
41 password=u'qweqwe',
44 password=u'qweqwe',
42 email=u'main_email@rhodecode.org',
45 email=u'main_email@rhodecode.org',
43 firstname=u'u1', lastname=u'u1')
46 firstname=u'u1', lastname=u'u1')
44 Session().commit()
47 Session().commit()
45
48
46 def do():
49 def do():
47 m = UserEmailMap()
50 m = UserEmailMap()
48 m.email = u'main_email@rhodecode.org'
51 m.email = u'main_email@rhodecode.org'
49 m.user = usr
52 m.user = usr
50 Session().add(m)
53 Session().add(m)
51 Session().commit()
54 Session().commit()
52 self.assertRaises(AttributeError, do)
55 self.assertRaises(AttributeError, do)
53
56
54 UserModel().delete(usr.user_id)
57 UserModel().delete(usr.user_id)
55 Session().commit()
58 Session().commit()
56
59
57 def test_extra_email_map(self):
60 def test_extra_email_map(self):
58 usr = UserModel().create_or_update(username=u'test_user',
61 usr = UserModel().create_or_update(username=u'test_user',
59 password=u'qweqwe',
62 password=u'qweqwe',
60 email=u'main_email@rhodecode.org',
63 email=u'main_email@rhodecode.org',
61 firstname=u'u1', lastname=u'u1')
64 firstname=u'u1', lastname=u'u1')
62 Session().commit()
65 Session().commit()
63
66
64 m = UserEmailMap()
67 m = UserEmailMap()
65 m.email = u'main_email2@rhodecode.org'
68 m.email = u'main_email2@rhodecode.org'
66 m.user = usr
69 m.user = usr
67 Session().add(m)
70 Session().add(m)
68 Session().commit()
71 Session().commit()
69
72
70 u = User.get_by_email(email='main_email@rhodecode.org')
73 u = User.get_by_email(email='main_email@rhodecode.org')
71 self.assertEqual(usr.user_id, u.user_id)
74 self.assertEqual(usr.user_id, u.user_id)
72 self.assertEqual(usr.username, u.username)
75 self.assertEqual(usr.username, u.username)
73
76
74 u = User.get_by_email(email='main_email2@rhodecode.org')
77 u = User.get_by_email(email='main_email2@rhodecode.org')
75 self.assertEqual(usr.user_id, u.user_id)
78 self.assertEqual(usr.user_id, u.user_id)
76 self.assertEqual(usr.username, u.username)
79 self.assertEqual(usr.username, u.username)
77 u = User.get_by_email(email='main_email3@rhodecode.org')
80 u = User.get_by_email(email='main_email3@rhodecode.org')
78 self.assertEqual(None, u)
81 self.assertEqual(None, u)
79
82
80 UserModel().delete(usr.user_id)
83 UserModel().delete(usr.user_id)
81 Session().commit()
84 Session().commit()
82
85
83
86
84 class TestUsers(unittest.TestCase):
87 class TestUsers(unittest.TestCase):
85
88
86 def __init__(self, methodName='runTest'):
89 def __init__(self, methodName='runTest'):
87 super(TestUsers, self).__init__(methodName=methodName)
90 super(TestUsers, self).__init__(methodName=methodName)
88
91
89 def setUp(self):
92 def setUp(self):
90 self.u1 = UserModel().create_or_update(username=u'u1',
93 self.u1 = UserModel().create_or_update(username=u'u1',
91 password=u'qweqwe',
94 password=u'qweqwe',
92 email=u'u1@rhodecode.org',
95 email=u'u1@rhodecode.org',
93 firstname=u'u1', lastname=u'u1')
96 firstname=u'u1', lastname=u'u1')
94
97
95 def tearDown(self):
98 def tearDown(self):
96 perm = Permission.query().all()
99 perm = Permission.query().all()
97 for p in perm:
100 for p in perm:
98 UserModel().revoke_perm(self.u1, p)
101 UserModel().revoke_perm(self.u1, p)
99
102
100 UserModel().delete(self.u1)
103 UserModel().delete(self.u1)
101 Session().commit()
104 Session().commit()
105 Session.remove()
102
106
103 def test_add_perm(self):
107 def test_add_perm(self):
104 perm = Permission.query().all()[0]
108 perm = Permission.query().all()[0]
105 UserModel().grant_perm(self.u1, perm)
109 UserModel().grant_perm(self.u1, perm)
106 Session().commit()
110 Session().commit()
107 self.assertEqual(UserModel().has_perm(self.u1, perm), True)
111 self.assertEqual(UserModel().has_perm(self.u1, perm), True)
108
112
109 def test_has_perm(self):
113 def test_has_perm(self):
110 perm = Permission.query().all()
114 perm = Permission.query().all()
111 for p in perm:
115 for p in perm:
112 has_p = UserModel().has_perm(self.u1, p)
116 has_p = UserModel().has_perm(self.u1, p)
113 self.assertEqual(False, has_p)
117 self.assertEqual(False, has_p)
114
118
115 def test_revoke_perm(self):
119 def test_revoke_perm(self):
116 perm = Permission.query().all()[0]
120 perm = Permission.query().all()[0]
117 UserModel().grant_perm(self.u1, perm)
121 UserModel().grant_perm(self.u1, perm)
118 Session().commit()
122 Session().commit()
119 self.assertEqual(UserModel().has_perm(self.u1, perm), True)
123 self.assertEqual(UserModel().has_perm(self.u1, perm), True)
120
124
121 #revoke
125 #revoke
122 UserModel().revoke_perm(self.u1, perm)
126 UserModel().revoke_perm(self.u1, perm)
123 Session().commit()
127 Session().commit()
124 self.assertEqual(UserModel().has_perm(self.u1, perm), False)
128 self.assertEqual(UserModel().has_perm(self.u1, perm), False)
@@ -1,249 +1,248 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 import unittest
2 import unittest
3 import formencode
3 import formencode
4
4
5 from rhodecode.tests import *
5 from rhodecode.tests import *
6
6
7 from rhodecode.model import validators as v
7 from rhodecode.model import validators as v
8 from rhodecode.model.users_group import UserGroupModel
8 from rhodecode.model.users_group import UserGroupModel
9
9
10 from rhodecode.model.meta import Session
10 from rhodecode.model.meta import Session
11 from rhodecode.model.repos_group import ReposGroupModel
11 from rhodecode.model.repos_group import ReposGroupModel
12 from rhodecode.config.routing import ADMIN_PREFIX
12 from rhodecode.config.routing import ADMIN_PREFIX
13 from rhodecode.model.db import ChangesetStatus, Repository
13 from rhodecode.model.db import ChangesetStatus, Repository
14 from rhodecode.model.changeset_status import ChangesetStatusModel
14 from rhodecode.model.changeset_status import ChangesetStatusModel
15 from rhodecode.model.comment import ChangesetCommentsModel
16
15
17
16
18 class TestReposGroups(unittest.TestCase):
17 class TestReposGroups(unittest.TestCase):
19
18
20 def setUp(self):
19 def setUp(self):
21 pass
20 pass
22
21
23 def tearDown(self):
22 def tearDown(self):
24 pass
23 Session.remove()
25
24
26 def test_Message_extractor(self):
25 def test_Message_extractor(self):
27 validator = v.ValidUsername()
26 validator = v.ValidUsername()
28 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
27 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
29
28
30 class StateObj(object):
29 class StateObj(object):
31 pass
30 pass
32
31
33 self.assertRaises(formencode.Invalid,
32 self.assertRaises(formencode.Invalid,
34 validator.to_python, 'default', StateObj)
33 validator.to_python, 'default', StateObj)
35
34
36 def test_ValidUsername(self):
35 def test_ValidUsername(self):
37 validator = v.ValidUsername()
36 validator = v.ValidUsername()
38
37
39 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
38 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
40 self.assertRaises(formencode.Invalid, validator.to_python, 'new_user')
39 self.assertRaises(formencode.Invalid, validator.to_python, 'new_user')
41 self.assertRaises(formencode.Invalid, validator.to_python, '.,')
40 self.assertRaises(formencode.Invalid, validator.to_python, '.,')
42 self.assertRaises(formencode.Invalid, validator.to_python,
41 self.assertRaises(formencode.Invalid, validator.to_python,
43 TEST_USER_ADMIN_LOGIN)
42 TEST_USER_ADMIN_LOGIN)
44 self.assertEqual('test', validator.to_python('test'))
43 self.assertEqual('test', validator.to_python('test'))
45
44
46 validator = v.ValidUsername(edit=True, old_data={'user_id': 1})
45 validator = v.ValidUsername(edit=True, old_data={'user_id': 1})
47
46
48 def test_ValidRepoUser(self):
47 def test_ValidRepoUser(self):
49 validator = v.ValidRepoUser()
48 validator = v.ValidRepoUser()
50 self.assertRaises(formencode.Invalid, validator.to_python, 'nouser')
49 self.assertRaises(formencode.Invalid, validator.to_python, 'nouser')
51 self.assertEqual(TEST_USER_ADMIN_LOGIN,
50 self.assertEqual(TEST_USER_ADMIN_LOGIN,
52 validator.to_python(TEST_USER_ADMIN_LOGIN))
51 validator.to_python(TEST_USER_ADMIN_LOGIN))
53
52
54 def test_ValidUserGroup(self):
53 def test_ValidUserGroup(self):
55 validator = v.ValidUserGroup()
54 validator = v.ValidUserGroup()
56 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
55 self.assertRaises(formencode.Invalid, validator.to_python, 'default')
57 self.assertRaises(formencode.Invalid, validator.to_python, '.,')
56 self.assertRaises(formencode.Invalid, validator.to_python, '.,')
58
57
59 gr = UserGroupModel().create('test')
58 gr = UserGroupModel().create('test')
60 gr2 = UserGroupModel().create('tes2')
59 gr2 = UserGroupModel().create('tes2')
61 Session.commit()
60 Session.commit()
62 self.assertRaises(formencode.Invalid, validator.to_python, 'test')
61 self.assertRaises(formencode.Invalid, validator.to_python, 'test')
63 assert gr.users_group_id != None
62 assert gr.users_group_id != None
64 validator = v.ValidUserGroup(edit=True,
63 validator = v.ValidUserGroup(edit=True,
65 old_data={'users_group_id':
64 old_data={'users_group_id':
66 gr2.users_group_id})
65 gr2.users_group_id})
67
66
68 self.assertRaises(formencode.Invalid, validator.to_python, 'test')
67 self.assertRaises(formencode.Invalid, validator.to_python, 'test')
69 self.assertRaises(formencode.Invalid, validator.to_python, 'TesT')
68 self.assertRaises(formencode.Invalid, validator.to_python, 'TesT')
70 self.assertRaises(formencode.Invalid, validator.to_python, 'TEST')
69 self.assertRaises(formencode.Invalid, validator.to_python, 'TEST')
71 UserGroupModel().delete(gr)
70 UserGroupModel().delete(gr)
72 UserGroupModel().delete(gr2)
71 UserGroupModel().delete(gr2)
73 Session.commit()
72 Session.commit()
74
73
75 def test_ValidReposGroup(self):
74 def test_ValidReposGroup(self):
76 validator = v.ValidReposGroup()
75 validator = v.ValidReposGroup()
77 model = ReposGroupModel()
76 model = ReposGroupModel()
78 self.assertRaises(formencode.Invalid, validator.to_python,
77 self.assertRaises(formencode.Invalid, validator.to_python,
79 {'group_name': HG_REPO, })
78 {'group_name': HG_REPO, })
80 gr = model.create(group_name='test_gr', group_description='desc',
79 gr = model.create(group_name='test_gr', group_description='desc',
81 parent=None,
80 parent=None,
82 just_db=True,
81 just_db=True,
83 owner=TEST_USER_ADMIN_LOGIN)
82 owner=TEST_USER_ADMIN_LOGIN)
84 self.assertRaises(formencode.Invalid,
83 self.assertRaises(formencode.Invalid,
85 validator.to_python, {'group_name': gr.group_name, })
84 validator.to_python, {'group_name': gr.group_name, })
86
85
87 validator = v.ValidReposGroup(edit=True,
86 validator = v.ValidReposGroup(edit=True,
88 old_data={'group_id': gr.group_id})
87 old_data={'group_id': gr.group_id})
89 self.assertRaises(formencode.Invalid,
88 self.assertRaises(formencode.Invalid,
90 validator.to_python, {
89 validator.to_python, {
91 'group_name': gr.group_name + 'n',
90 'group_name': gr.group_name + 'n',
92 'group_parent_id': gr.group_id
91 'group_parent_id': gr.group_id
93 })
92 })
94 model.delete(gr)
93 model.delete(gr)
95
94
96 def test_ValidPassword(self):
95 def test_ValidPassword(self):
97 validator = v.ValidPassword()
96 validator = v.ValidPassword()
98 self.assertEqual('lol', validator.to_python('lol'))
97 self.assertEqual('lol', validator.to_python('lol'))
99 self.assertEqual(None, validator.to_python(None))
98 self.assertEqual(None, validator.to_python(None))
100 self.assertRaises(formencode.Invalid, validator.to_python, 'Δ…Δ‡ΕΌΕΊ')
99 self.assertRaises(formencode.Invalid, validator.to_python, 'Δ…Δ‡ΕΌΕΊ')
101
100
102 def test_ValidPasswordsMatch(self):
101 def test_ValidPasswordsMatch(self):
103 validator = v.ValidPasswordsMatch()
102 validator = v.ValidPasswordsMatch()
104 self.assertRaises(formencode.Invalid,
103 self.assertRaises(formencode.Invalid,
105 validator.to_python, {'password': 'pass',
104 validator.to_python, {'password': 'pass',
106 'password_confirmation': 'pass2'})
105 'password_confirmation': 'pass2'})
107
106
108 self.assertRaises(formencode.Invalid,
107 self.assertRaises(formencode.Invalid,
109 validator.to_python, {'new_password': 'pass',
108 validator.to_python, {'new_password': 'pass',
110 'password_confirmation': 'pass2'})
109 'password_confirmation': 'pass2'})
111
110
112 self.assertEqual({'new_password': 'pass',
111 self.assertEqual({'new_password': 'pass',
113 'password_confirmation': 'pass'},
112 'password_confirmation': 'pass'},
114 validator.to_python({'new_password': 'pass',
113 validator.to_python({'new_password': 'pass',
115 'password_confirmation': 'pass'}))
114 'password_confirmation': 'pass'}))
116
115
117 self.assertEqual({'password': 'pass',
116 self.assertEqual({'password': 'pass',
118 'password_confirmation': 'pass'},
117 'password_confirmation': 'pass'},
119 validator.to_python({'password': 'pass',
118 validator.to_python({'password': 'pass',
120 'password_confirmation': 'pass'}))
119 'password_confirmation': 'pass'}))
121
120
122 def test_ValidAuth(self):
121 def test_ValidAuth(self):
123 validator = v.ValidAuth()
122 validator = v.ValidAuth()
124 valid_creds = {
123 valid_creds = {
125 'username': TEST_USER_REGULAR2_LOGIN,
124 'username': TEST_USER_REGULAR2_LOGIN,
126 'password': TEST_USER_REGULAR2_PASS,
125 'password': TEST_USER_REGULAR2_PASS,
127 }
126 }
128 invalid_creds = {
127 invalid_creds = {
129 'username': 'err',
128 'username': 'err',
130 'password': 'err',
129 'password': 'err',
131 }
130 }
132 self.assertEqual(valid_creds, validator.to_python(valid_creds))
131 self.assertEqual(valid_creds, validator.to_python(valid_creds))
133 self.assertRaises(formencode.Invalid,
132 self.assertRaises(formencode.Invalid,
134 validator.to_python, invalid_creds)
133 validator.to_python, invalid_creds)
135
134
136 def test_ValidAuthToken(self):
135 def test_ValidAuthToken(self):
137 validator = v.ValidAuthToken()
136 validator = v.ValidAuthToken()
138 # this is untestable without a threadlocal
137 # this is untestable without a threadlocal
139 # self.assertRaises(formencode.Invalid,
138 # self.assertRaises(formencode.Invalid,
140 # validator.to_python, 'BadToken')
139 # validator.to_python, 'BadToken')
141 validator
140 validator
142
141
143 def test_ValidRepoName(self):
142 def test_ValidRepoName(self):
144 validator = v.ValidRepoName()
143 validator = v.ValidRepoName()
145
144
146 self.assertRaises(formencode.Invalid,
145 self.assertRaises(formencode.Invalid,
147 validator.to_python, {'repo_name': ''})
146 validator.to_python, {'repo_name': ''})
148
147
149 self.assertRaises(formencode.Invalid,
148 self.assertRaises(formencode.Invalid,
150 validator.to_python, {'repo_name': HG_REPO})
149 validator.to_python, {'repo_name': HG_REPO})
151
150
152 gr = ReposGroupModel().create(group_name='group_test',
151 gr = ReposGroupModel().create(group_name='group_test',
153 group_description='desc',
152 group_description='desc',
154 parent=None,
153 parent=None,
155 owner=TEST_USER_ADMIN_LOGIN)
154 owner=TEST_USER_ADMIN_LOGIN)
156 self.assertRaises(formencode.Invalid,
155 self.assertRaises(formencode.Invalid,
157 validator.to_python, {'repo_name': gr.group_name})
156 validator.to_python, {'repo_name': gr.group_name})
158
157
159 #TODO: write an error case for that ie. create a repo withinh a group
158 #TODO: write an error case for that ie. create a repo withinh a group
160 # self.assertRaises(formencode.Invalid,
159 # self.assertRaises(formencode.Invalid,
161 # validator.to_python, {'repo_name': 'some',
160 # validator.to_python, {'repo_name': 'some',
162 # 'repo_group': gr.group_id})
161 # 'repo_group': gr.group_id})
163
162
164 def test_ValidForkName(self):
163 def test_ValidForkName(self):
165 # this uses ValidRepoName validator
164 # this uses ValidRepoName validator
166 assert True
165 assert True
167
166
168 @parameterized.expand([
167 @parameterized.expand([
169 ('test', 'test'), ('lolz!', 'lolz'), (' aavv', 'aavv'),
168 ('test', 'test'), ('lolz!', 'lolz'), (' aavv', 'aavv'),
170 ('ala ma kota', 'ala-ma-kota'), ('@nooo', 'nooo'),
169 ('ala ma kota', 'ala-ma-kota'), ('@nooo', 'nooo'),
171 ('$!haha lolz !', 'haha-lolz'), ('$$$$$', ''), ('{}OK!', 'OK'),
170 ('$!haha lolz !', 'haha-lolz'), ('$$$$$', ''), ('{}OK!', 'OK'),
172 ('/]re po', 're-po')])
171 ('/]re po', 're-po')])
173 def test_SlugifyName(self, name, expected):
172 def test_SlugifyName(self, name, expected):
174 validator = v.SlugifyName()
173 validator = v.SlugifyName()
175 self.assertEqual(expected, validator.to_python(name))
174 self.assertEqual(expected, validator.to_python(name))
176
175
177 def test_ValidCloneUri(self):
176 def test_ValidCloneUri(self):
178 #TODO: write this one
177 #TODO: write this one
179 pass
178 pass
180
179
181 def test_ValidForkType(self):
180 def test_ValidForkType(self):
182 validator = v.ValidForkType(old_data={'repo_type': 'hg'})
181 validator = v.ValidForkType(old_data={'repo_type': 'hg'})
183 self.assertEqual('hg', validator.to_python('hg'))
182 self.assertEqual('hg', validator.to_python('hg'))
184 self.assertRaises(formencode.Invalid, validator.to_python, 'git')
183 self.assertRaises(formencode.Invalid, validator.to_python, 'git')
185
184
186 def test_ValidPerms(self):
185 def test_ValidPerms(self):
187 #TODO: write this one
186 #TODO: write this one
188 pass
187 pass
189
188
190 def test_ValidSettings(self):
189 def test_ValidSettings(self):
191 validator = v.ValidSettings()
190 validator = v.ValidSettings()
192 self.assertEqual({'pass': 'pass'},
191 self.assertEqual({'pass': 'pass'},
193 validator.to_python(value={'user': 'test',
192 validator.to_python(value={'user': 'test',
194 'pass': 'pass'}))
193 'pass': 'pass'}))
195
194
196 self.assertEqual({'user2': 'test', 'pass': 'pass'},
195 self.assertEqual({'user2': 'test', 'pass': 'pass'},
197 validator.to_python(value={'user2': 'test',
196 validator.to_python(value={'user2': 'test',
198 'pass': 'pass'}))
197 'pass': 'pass'}))
199
198
200 def test_ValidPath(self):
199 def test_ValidPath(self):
201 validator = v.ValidPath()
200 validator = v.ValidPath()
202 self.assertEqual(TESTS_TMP_PATH,
201 self.assertEqual(TESTS_TMP_PATH,
203 validator.to_python(TESTS_TMP_PATH))
202 validator.to_python(TESTS_TMP_PATH))
204 self.assertRaises(formencode.Invalid, validator.to_python,
203 self.assertRaises(formencode.Invalid, validator.to_python,
205 '/no_such_dir')
204 '/no_such_dir')
206
205
207 def test_UniqSystemEmail(self):
206 def test_UniqSystemEmail(self):
208 validator = v.UniqSystemEmail(old_data={})
207 validator = v.UniqSystemEmail(old_data={})
209
208
210 self.assertEqual('mail@python.org',
209 self.assertEqual('mail@python.org',
211 validator.to_python('MaiL@Python.org'))
210 validator.to_python('MaiL@Python.org'))
212
211
213 email = TEST_USER_REGULAR2_EMAIL
212 email = TEST_USER_REGULAR2_EMAIL
214 self.assertRaises(formencode.Invalid, validator.to_python, email)
213 self.assertRaises(formencode.Invalid, validator.to_python, email)
215
214
216 def test_ValidSystemEmail(self):
215 def test_ValidSystemEmail(self):
217 validator = v.ValidSystemEmail()
216 validator = v.ValidSystemEmail()
218 email = TEST_USER_REGULAR2_EMAIL
217 email = TEST_USER_REGULAR2_EMAIL
219
218
220 self.assertEqual(email, validator.to_python(email))
219 self.assertEqual(email, validator.to_python(email))
221 self.assertRaises(formencode.Invalid, validator.to_python, 'err')
220 self.assertRaises(formencode.Invalid, validator.to_python, 'err')
222
221
223 def test_LdapLibValidator(self):
222 def test_LdapLibValidator(self):
224 validator = v.LdapLibValidator()
223 validator = v.LdapLibValidator()
225 self.assertRaises(v.LdapImportError, validator.to_python, 'err')
224 self.assertRaises(v.LdapImportError, validator.to_python, 'err')
226
225
227 def test_AttrLoginValidator(self):
226 def test_AttrLoginValidator(self):
228 validator = v.AttrLoginValidator()
227 validator = v.AttrLoginValidator()
229 self.assertRaises(formencode.Invalid, validator.to_python, 123)
228 self.assertRaises(formencode.Invalid, validator.to_python, 123)
230
229
231 def test_NotReviewedRevisions(self):
230 def test_NotReviewedRevisions(self):
232 repo_id = Repository.get_by_repo_name(HG_REPO).repo_id
231 repo_id = Repository.get_by_repo_name(HG_REPO).repo_id
233 validator = v.NotReviewedRevisions(repo_id)
232 validator = v.NotReviewedRevisions(repo_id)
234 rev = '0' * 40
233 rev = '0' * 40
235 # add status for a rev, that should throw an error because it is already
234 # add status for a rev, that should throw an error because it is already
236 # reviewed
235 # reviewed
237 new_status = ChangesetStatus()
236 new_status = ChangesetStatus()
238 new_status.author = ChangesetStatusModel()._get_user(TEST_USER_ADMIN_LOGIN)
237 new_status.author = ChangesetStatusModel()._get_user(TEST_USER_ADMIN_LOGIN)
239 new_status.repo = ChangesetStatusModel()._get_repo(HG_REPO)
238 new_status.repo = ChangesetStatusModel()._get_repo(HG_REPO)
240 new_status.status = ChangesetStatus.STATUS_APPROVED
239 new_status.status = ChangesetStatus.STATUS_APPROVED
241 new_status.comment = None
240 new_status.comment = None
242 new_status.revision = rev
241 new_status.revision = rev
243 Session().add(new_status)
242 Session().add(new_status)
244 Session().commit()
243 Session().commit()
245 try:
244 try:
246 self.assertRaises(formencode.Invalid, validator.to_python, [rev])
245 self.assertRaises(formencode.Invalid, validator.to_python, [rev])
247 finally:
246 finally:
248 Session().delete(new_status)
247 Session().delete(new_status)
249 Session().commit()
248 Session().commit()
General Comments 0
You need to be logged in to leave comments. Login now