##// END OF EJS Templates
tests: improve assert_flash_message call when called with no_ and empty flash is present.
marcink -
r2349:d77ebe76 default
parent child Browse files
Show More
@@ -1,247 +1,251 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2017 RhodeCode GmbH
3 # Copyright (C) 2010-2017 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import os
21 import os
22 import time
22 import time
23 import logging
23 import logging
24 import datetime
24 import datetime
25 import hashlib
25 import hashlib
26 import tempfile
26 import tempfile
27 from os.path import join as jn
27 from os.path import join as jn
28
28
29 from tempfile import _RandomNameSequence
29 from tempfile import _RandomNameSequence
30
30
31 from pylons import url
31 from pylons import url
32
32
33 import pytest
33 import pytest
34
34
35 from rhodecode.model.db import User
35 from rhodecode.model.db import User
36 from rhodecode.lib import auth
36 from rhodecode.lib import auth
37 from rhodecode.lib import helpers as h
37 from rhodecode.lib import helpers as h
38 from rhodecode.lib.helpers import flash, link_to
38 from rhodecode.lib.helpers import flash, link_to
39 from rhodecode.lib.utils2 import safe_str
39 from rhodecode.lib.utils2 import safe_str
40
40
41
41
42 log = logging.getLogger(__name__)
42 log = logging.getLogger(__name__)
43
43
44 __all__ = [
44 __all__ = [
45 'get_new_dir', 'TestController',
45 'get_new_dir', 'TestController',
46 'url', 'link_to', 'ldap_lib_installed', 'clear_all_caches',
46 'url', 'link_to', 'ldap_lib_installed', 'clear_all_caches',
47 'assert_session_flash', 'login_user', 'no_newline_id_generator',
47 'assert_session_flash', 'login_user', 'no_newline_id_generator',
48 'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'SVN_REPO',
48 'TESTS_TMP_PATH', 'HG_REPO', 'GIT_REPO', 'SVN_REPO',
49 'NEW_HG_REPO', 'NEW_GIT_REPO',
49 'NEW_HG_REPO', 'NEW_GIT_REPO',
50 'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
50 'HG_FORK', 'GIT_FORK', 'TEST_USER_ADMIN_LOGIN', 'TEST_USER_ADMIN_PASS',
51 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
51 'TEST_USER_REGULAR_LOGIN', 'TEST_USER_REGULAR_PASS',
52 'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
52 'TEST_USER_REGULAR_EMAIL', 'TEST_USER_REGULAR2_LOGIN',
53 'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
53 'TEST_USER_REGULAR2_PASS', 'TEST_USER_REGULAR2_EMAIL', 'TEST_HG_REPO',
54 'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
54 'TEST_HG_REPO_CLONE', 'TEST_HG_REPO_PULL', 'TEST_GIT_REPO',
55 'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'SCM_TESTS',
55 'TEST_GIT_REPO_CLONE', 'TEST_GIT_REPO_PULL', 'SCM_TESTS',
56 ]
56 ]
57
57
58 # Invoke websetup with the current config file
58 # Invoke websetup with the current config file
59 # SetupCommand('setup-app').run([config_file])
59 # SetupCommand('setup-app').run([config_file])
60
60
61 # SOME GLOBALS FOR TESTS
61 # SOME GLOBALS FOR TESTS
62 TEST_DIR = tempfile.gettempdir()
62 TEST_DIR = tempfile.gettempdir()
63
63
64 TESTS_TMP_PATH = jn(TEST_DIR, 'rc_test_%s' % _RandomNameSequence().next())
64 TESTS_TMP_PATH = jn(TEST_DIR, 'rc_test_%s' % _RandomNameSequence().next())
65 TEST_USER_ADMIN_LOGIN = 'test_admin'
65 TEST_USER_ADMIN_LOGIN = 'test_admin'
66 TEST_USER_ADMIN_PASS = 'test12'
66 TEST_USER_ADMIN_PASS = 'test12'
67 TEST_USER_ADMIN_EMAIL = 'test_admin@mail.com'
67 TEST_USER_ADMIN_EMAIL = 'test_admin@mail.com'
68
68
69 TEST_USER_REGULAR_LOGIN = 'test_regular'
69 TEST_USER_REGULAR_LOGIN = 'test_regular'
70 TEST_USER_REGULAR_PASS = 'test12'
70 TEST_USER_REGULAR_PASS = 'test12'
71 TEST_USER_REGULAR_EMAIL = 'test_regular@mail.com'
71 TEST_USER_REGULAR_EMAIL = 'test_regular@mail.com'
72
72
73 TEST_USER_REGULAR2_LOGIN = 'test_regular2'
73 TEST_USER_REGULAR2_LOGIN = 'test_regular2'
74 TEST_USER_REGULAR2_PASS = 'test12'
74 TEST_USER_REGULAR2_PASS = 'test12'
75 TEST_USER_REGULAR2_EMAIL = 'test_regular2@mail.com'
75 TEST_USER_REGULAR2_EMAIL = 'test_regular2@mail.com'
76
76
77 HG_REPO = 'vcs_test_hg'
77 HG_REPO = 'vcs_test_hg'
78 GIT_REPO = 'vcs_test_git'
78 GIT_REPO = 'vcs_test_git'
79 SVN_REPO = 'vcs_test_svn'
79 SVN_REPO = 'vcs_test_svn'
80
80
81 NEW_HG_REPO = 'vcs_test_hg_new'
81 NEW_HG_REPO = 'vcs_test_hg_new'
82 NEW_GIT_REPO = 'vcs_test_git_new'
82 NEW_GIT_REPO = 'vcs_test_git_new'
83
83
84 HG_FORK = 'vcs_test_hg_fork'
84 HG_FORK = 'vcs_test_hg_fork'
85 GIT_FORK = 'vcs_test_git_fork'
85 GIT_FORK = 'vcs_test_git_fork'
86
86
87 ## VCS
87 ## VCS
88 SCM_TESTS = ['hg', 'git']
88 SCM_TESTS = ['hg', 'git']
89 uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
89 uniq_suffix = str(int(time.mktime(datetime.datetime.now().timetuple())))
90
90
91 TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
91 TEST_GIT_REPO = jn(TESTS_TMP_PATH, GIT_REPO)
92 TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
92 TEST_GIT_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcsgitclone%s' % uniq_suffix)
93 TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
93 TEST_GIT_REPO_PULL = jn(TESTS_TMP_PATH, 'vcsgitpull%s' % uniq_suffix)
94
94
95 TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
95 TEST_HG_REPO = jn(TESTS_TMP_PATH, HG_REPO)
96 TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
96 TEST_HG_REPO_CLONE = jn(TESTS_TMP_PATH, 'vcshgclone%s' % uniq_suffix)
97 TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
97 TEST_HG_REPO_PULL = jn(TESTS_TMP_PATH, 'vcshgpull%s' % uniq_suffix)
98
98
99 TEST_REPO_PREFIX = 'vcs-test'
99 TEST_REPO_PREFIX = 'vcs-test'
100
100
101
101
102 # skip ldap tests if LDAP lib is not installed
102 # skip ldap tests if LDAP lib is not installed
103 ldap_lib_installed = False
103 ldap_lib_installed = False
104 try:
104 try:
105 import ldap
105 import ldap
106 ldap_lib_installed = True
106 ldap_lib_installed = True
107 except ImportError:
107 except ImportError:
108 ldap = None
108 ldap = None
109 # means that python-ldap is not installed
109 # means that python-ldap is not installed
110 pass
110 pass
111
111
112
112
113 def clear_all_caches():
113 def clear_all_caches():
114 from beaker.cache import cache_managers
114 from beaker.cache import cache_managers
115 for _cache in cache_managers.values():
115 for _cache in cache_managers.values():
116 _cache.clear()
116 _cache.clear()
117
117
118
118
119 def get_new_dir(title):
119 def get_new_dir(title):
120 """
120 """
121 Returns always new directory path.
121 Returns always new directory path.
122 """
122 """
123 from rhodecode.tests.vcs.utils import get_normalized_path
123 from rhodecode.tests.vcs.utils import get_normalized_path
124 name_parts = [TEST_REPO_PREFIX]
124 name_parts = [TEST_REPO_PREFIX]
125 if title:
125 if title:
126 name_parts.append(title)
126 name_parts.append(title)
127 hex_str = hashlib.sha1('%s %s' % (os.getpid(), time.time())).hexdigest()
127 hex_str = hashlib.sha1('%s %s' % (os.getpid(), time.time())).hexdigest()
128 name_parts.append(hex_str)
128 name_parts.append(hex_str)
129 name = '-'.join(name_parts)
129 name = '-'.join(name_parts)
130 path = os.path.join(TEST_DIR, name)
130 path = os.path.join(TEST_DIR, name)
131 return get_normalized_path(path)
131 return get_normalized_path(path)
132
132
133
133
134 @pytest.mark.usefixtures('app', 'index_location')
134 @pytest.mark.usefixtures('app', 'index_location')
135 class TestController(object):
135 class TestController(object):
136
136
137 maxDiff = None
137 maxDiff = None
138
138
139 def log_user(self, username=TEST_USER_ADMIN_LOGIN,
139 def log_user(self, username=TEST_USER_ADMIN_LOGIN,
140 password=TEST_USER_ADMIN_PASS):
140 password=TEST_USER_ADMIN_PASS):
141 self._logged_username = username
141 self._logged_username = username
142 self._session = login_user_session(self.app, username, password)
142 self._session = login_user_session(self.app, username, password)
143 self.csrf_token = auth.get_csrf_token(self._session)
143 self.csrf_token = auth.get_csrf_token(self._session)
144
144
145 return self._session['rhodecode_user']
145 return self._session['rhodecode_user']
146
146
147 def logout_user(self):
147 def logout_user(self):
148 logout_user_session(self.app, auth.get_csrf_token(self._session))
148 logout_user_session(self.app, auth.get_csrf_token(self._session))
149 self.csrf_token = None
149 self.csrf_token = None
150 self._logged_username = None
150 self._logged_username = None
151 self._session = None
151 self._session = None
152
152
153 def _get_logged_user(self):
153 def _get_logged_user(self):
154 return User.get_by_username(self._logged_username)
154 return User.get_by_username(self._logged_username)
155
155
156
156
157 def login_user_session(
157 def login_user_session(
158 app, username=TEST_USER_ADMIN_LOGIN, password=TEST_USER_ADMIN_PASS):
158 app, username=TEST_USER_ADMIN_LOGIN, password=TEST_USER_ADMIN_PASS):
159
159
160 response = app.post(
160 response = app.post(
161 h.route_path('login'),
161 h.route_path('login'),
162 {'username': username, 'password': password})
162 {'username': username, 'password': password})
163 if 'invalid user name' in response.body:
163 if 'invalid user name' in response.body:
164 pytest.fail('could not login using %s %s' % (username, password))
164 pytest.fail('could not login using %s %s' % (username, password))
165
165
166 assert response.status == '302 Found'
166 assert response.status == '302 Found'
167 response = response.follow()
167 response = response.follow()
168 assert response.status == '200 OK'
168 assert response.status == '200 OK'
169
169
170 session = response.get_session_from_response()
170 session = response.get_session_from_response()
171 assert 'rhodecode_user' in session
171 assert 'rhodecode_user' in session
172 rc_user = session['rhodecode_user']
172 rc_user = session['rhodecode_user']
173 assert rc_user.get('username') == username
173 assert rc_user.get('username') == username
174 assert rc_user.get('is_authenticated')
174 assert rc_user.get('is_authenticated')
175
175
176 return session
176 return session
177
177
178
178
179 def logout_user_session(app, csrf_token):
179 def logout_user_session(app, csrf_token):
180 app.post(h.route_path('logout'), {'csrf_token': csrf_token}, status=302)
180 app.post(h.route_path('logout'), {'csrf_token': csrf_token}, status=302)
181
181
182
182
183 def login_user(app, username=TEST_USER_ADMIN_LOGIN,
183 def login_user(app, username=TEST_USER_ADMIN_LOGIN,
184 password=TEST_USER_ADMIN_PASS):
184 password=TEST_USER_ADMIN_PASS):
185 return login_user_session(app, username, password)['rhodecode_user']
185 return login_user_session(app, username, password)['rhodecode_user']
186
186
187
187
188 def assert_session_flash(response, msg=None, category=None, no_=None):
188 def assert_session_flash(response, msg=None, category=None, no_=None):
189 """
189 """
190 Assert on a flash message in the current session.
190 Assert on a flash message in the current session.
191
191
192 :param response: Response from give calll, it will contain flash
192 :param response: Response from give calll, it will contain flash
193 messages or bound session with them.
193 messages or bound session with them.
194 :param msg: The expected message. Will be evaluated if a
194 :param msg: The expected message. Will be evaluated if a
195 :class:`LazyString` is passed in.
195 :class:`LazyString` is passed in.
196 :param category: Optional. If passed, the message category will be
196 :param category: Optional. If passed, the message category will be
197 checked as well.
197 checked as well.
198 :param no_: Optional. If passed, the message will be checked to NOT
198 :param no_: Optional. If passed, the message will be checked to NOT
199 be in the flash session
199 be in the flash session
200 """
200 """
201 if msg is None and no_ is None:
201 if msg is None and no_ is None:
202 raise ValueError("Parameter msg or no_ is required.")
202 raise ValueError("Parameter msg or no_ is required.")
203
203
204 if msg and no_:
204 if msg and no_:
205 raise ValueError("Please specify either msg or no_, but not both")
205 raise ValueError("Please specify either msg or no_, but not both")
206
206
207 session = response.get_session_from_response()
207 session = response.get_session_from_response()
208 messages = flash.pop_messages(session=session)
208 messages = flash.pop_messages(session=session)
209 msg = _eval_if_lazy(msg)
209 msg = _eval_if_lazy(msg)
210
210
211 assert messages, 'unable to find message `%s` in empty flash list' % msg
211 if no_:
212 error_msg = 'unable to detect no_ message `%s` in empty flash list' % no_
213 else:
214 error_msg = 'unable to find message `%s` in empty flash list' % msg
215 assert messages, error_msg
212 message = messages[0]
216 message = messages[0]
213
217
214 message_text = _eval_if_lazy(message.message) or ''
218 message_text = _eval_if_lazy(message.message) or ''
215
219
216 if no_:
220 if no_:
217 if no_ in message_text:
221 if no_ in message_text:
218 msg = u'msg `%s` found in session flash.' % (no_,)
222 msg = u'msg `%s` found in session flash.' % (no_,)
219 pytest.fail(safe_str(msg))
223 pytest.fail(safe_str(msg))
220 else:
224 else:
221 if msg not in message_text:
225 if msg not in message_text:
222 fail_msg = u'msg `%s` not found in session ' \
226 fail_msg = u'msg `%s` not found in session ' \
223 u'flash: got `%s` (type:%s) instead' % (
227 u'flash: got `%s` (type:%s) instead' % (
224 msg, message_text, type(message_text))
228 msg, message_text, type(message_text))
225
229
226 pytest.fail(safe_str(fail_msg))
230 pytest.fail(safe_str(fail_msg))
227 if category:
231 if category:
228 assert category == message.category
232 assert category == message.category
229
233
230
234
231 def _eval_if_lazy(value):
235 def _eval_if_lazy(value):
232 return value.eval() if hasattr(value, 'eval') else value
236 return value.eval() if hasattr(value, 'eval') else value
233
237
234
238
235 def no_newline_id_generator(test_name):
239 def no_newline_id_generator(test_name):
236 """
240 """
237 Generates a test name without spaces or newlines characters. Used for
241 Generates a test name without spaces or newlines characters. Used for
238 nicer output of progress of test
242 nicer output of progress of test
239 """
243 """
240 org_name = test_name
244 org_name = test_name
241 test_name = test_name\
245 test_name = test_name\
242 .replace('\n', '_N') \
246 .replace('\n', '_N') \
243 .replace('\r', '_N') \
247 .replace('\r', '_N') \
244 .replace('\t', '_T') \
248 .replace('\t', '_T') \
245 .replace(' ', '_S')
249 .replace(' ', '_S')
246
250
247 return test_name or 'test-with-empty-name'
251 return test_name or 'test-with-empty-name'
General Comments 0
You need to be logged in to leave comments. Login now