This repository has been archived by the owner on Aug 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtests.py
291 lines (231 loc) · 11.6 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import slugify
from contextlib import contextmanager
from datetime import datetime
from urlparse import urlparse, parse_qs
import httpretty
from flask import url_for, session, current_app
from udata.auth import current_user
from udata.models import User
from udata.settings import Testing
from udata.core.user.factories import UserFactory
from udata.tests.frontend import FrontTestCase
from udata.utils import faker
from udata_youckan import init_app, encode_state, decode_state
class YouckanSettings(Testing):
TEST_WITH_PLUGINS = True
PLUGINS = ['youckan']
YOUCKAN_URL = 'https://youckan/'
YOUCKAN_CONSUMER_KEY = 'key',
YOUCKAN_CONSUMER_SECRET = 'secret'
YOUCKAN_AUTH_COOKIE = 'youckan.test.auth'
YOUCKAN_SESSION_COOKIE = 'youckan.test.session'
def youckan_api_response(**kwargs):
'''A YouCKAN ME API response factory'''
data = {
'profile': {
'website': faker.url(),
'city': faker.city(),
'about': faker.text(),
'avatar': faker.url() + 'avatar.png',
},
'first_name': faker.first_name(),
'last_name': faker.last_name(),
'email': faker.email(),
'is_active': True,
'is_superuser': False,
'date_joined': datetime.now().isoformat(),
'slug': None,
}
for key in data.keys():
if key in kwargs:
data[key] = kwargs[key]
data['fullname'] = ' '.join((data['first_name'], data['last_name']))
if not data['slug']:
data['slug'] = slugify.slugify(data['fullname'].lower())
return data
class YouckanTest(FrontTestCase):
settings = YouckanSettings
def create_app(self):
app = super(YouckanTest, self).create_app()
init_app(app)
return app
@contextmanager
def mock_authorize(self, **kwargs):
token = {
'access_token': 'token',
'token_type': 'Bearer',
'expires_in': '3600',
'refresh_token': 'refresh-token',
}
profile = youckan_api_response(**kwargs)
httpretty.register_uri(httpretty.POST, self.app.config['YOUCKAN_ACCESS_TOKEN_URL'],
body=json.dumps(token),
content_type='application/json'
)
httpretty.register_uri(httpretty.GET, self.app.config['YOUCKAN_BASE_URL'] + 'me',
body=json.dumps(profile),
content_type='application/json'
)
with self.app.test_client() as client:
yield profile, client
def test_login_redirect_to_youckan(self):
'''Login should redirect to youckan login'''
next_url = 'http://someurl/'
message = 'You should log in'
response = self.get(url_for('security.login', next=next_url, message=message))
self.assertStatus(response, 302)
response_url = urlparse(response.location)
qs = parse_qs(response_url.query)
expected_url = urlparse(YouckanSettings.YOUCKAN_URL + 'login')
self.assertEqual(response_url.hostname, expected_url.hostname)
self.assertEqual(response_url.path, expected_url.path)
self.assertEqual(qs['next'][0], next_url)
self.assertEqual(qs['message'][0], message)
def test_login_redirect_to_youckan_with_unicode(self):
'''Login should redirect to youckan login and support unicode'''
next_url = 'http://someurl/é€'
message = 'You should log in'
response = self.get(url_for('security.login', next=next_url, message=message))
self.assertStatus(response, 302)
response_url = urlparse(response.location)
qs = parse_qs(response_url.query)
expected_url = urlparse(YouckanSettings.YOUCKAN_URL + 'login')
self.assertEqual(response_url.hostname, expected_url.hostname)
self.assertEqual(response_url.path, expected_url.path)
self.assertEqual(qs['next'][0].decode('utf-8'), next_url)
self.assertEqual(qs['message'][0], message)
def test_login_redirect_to_youckan_with_path_only(self):
'''Login should redirect to youckan login and support unicode'''
next_url = '/é€'
message = 'You should log in'
response = self.get(url_for('security.login', next=next_url, message=message))
self.assertStatus(response, 302)
response_url = urlparse(response.location)
qs = parse_qs(response_url.query)
expected_url = urlparse(YouckanSettings.YOUCKAN_URL + 'login')
self.assertEqual(response_url.hostname, expected_url.hostname)
self.assertEqual(response_url.path, expected_url.path)
self.assertEqual(qs['next'][0].decode('utf-8'), 'https://localhost' + next_url)
self.assertEqual(qs['message'][0], message)
def test_login_required_redirect_to_youckan(self):
'''Login required decorator should redirect to youckan login'''
@self.app.route('/test-login-required/')
def test_login_required():
return current_app.login_manager.unauthorized() # Simulate the login required decorator
url = url_for('test_login_required')
response = self.get(url)
self.assertStatus(response, 302)
self.assertEqual(response.location, url_for('security.login', _external=True, next=url))
self.assert_not_flash()
def test_logout_redirect_to_youckan(self):
'''Logout should trigger a YouCKAN logout'''
with self.app.test_client() as client:
self.login(client=client)
response = self.get(url_for('security.logout'), base_url='https://localhost', client=client)
self.assertStatus(response, 302)
self.assertFalse(current_user.is_authenticated)
expected_url = urlparse(YouckanSettings.YOUCKAN_URL + 'logout')
response_url = urlparse(response.location)
self.assertEqual(response_url.hostname, expected_url.hostname)
self.assertEqual(response_url.path, expected_url.path)
@httpretty.activate
def test_log_user_on_authorize_callback(self):
'''Should log the user in on authorize callback'''
user = UserFactory()
with self.mock_authorize(email=user.email) as (profile, client):
response = self.get(url_for('youckan.authorized', code='code'), client=client)
self.assertRedirects(response, url_for('site.home'))
self.assertIn('youckan.token', session)
self.assertTrue(current_user.is_authenticated)
self.assertEqual(len(User.objects), 1)
@httpretty.activate
def test_update_user_on_authorize_callback(self):
'''Should only update specific field on authorize callback'''
user = UserFactory()
old_slug = user.slug
with self.mock_authorize(email=user.email, is_superuser=True) as (profile, client):
response = self.get(url_for('youckan.authorized', code='code'), client=client)
self.assertRedirects(response, url_for('site.home'))
self.assertIn('youckan.token', session)
self.assertTrue(current_user.is_authenticated)
user.reload()
self.assertEqual(user.slug, old_slug)
self.assertEqual(user.first_name, profile['first_name'])
self.assertEqual(user.last_name, profile['last_name'])
self.assertEqual(user.email, profile['email'])
self.assertEqual(user.avatar_url, profile['profile']['avatar'])
self.assertEqual(len(User.objects), 1)
@httpretty.activate
def test_log_admin_user_on_authorize_callback(self):
'''Should log the user with the admin role in on authorize callback'''
user = UserFactory()
with self.mock_authorize(email=user.email, is_superuser=True) as (profile, client):
response = self.get(url_for('youckan.authorized', code='code'), client=client)
self.assertRedirects(response, url_for('site.home'))
self.assertIn('youckan.token', session)
self.assertTrue(current_user.is_authenticated)
self.assertTrue(current_user.has_role('admin'))
self.assertEqual(len(User.objects), 1)
@httpretty.activate
def test_log_inactive_user_on_authorize_callback(self):
'''Should log the user with the admin role in on authorize callback'''
user = UserFactory(active=False)
with self.mock_authorize(email=user.email, is_active=True) as (profile, client):
response = self.get(url_for('youckan.authorized', code='code'), client=client)
self.assertRedirects(response, url_for('site.home'))
self.assertIn('youckan.token', session)
self.assertTrue(current_user.is_authenticated)
self.assertTrue(current_user.is_active)
self.assertEqual(len(User.objects), 1)
@httpretty.activate
def test_fetch_token_and_create_user_on_authorize_callback(self):
'''Should create the user on authorize callback'''
with self.mock_authorize() as (profile, client):
response = self.get(url_for('youckan.authorized', code='code'), client=client)
self.assertRedirects(response, url_for('site.home'))
self.assertIn('youckan.token', session)
self.assertTrue(current_user.is_authenticated)
self.assertTrue(current_user.is_active)
self.assertEqual(current_user.slug, profile['slug'])
self.assertEqual(current_user.first_name, profile['first_name'])
self.assertEqual(current_user.last_name, profile['last_name'])
self.assertEqual(current_user.email, profile['email'])
self.assertEqual(current_user.has_role('admin'), profile['is_superuser'])
self.assertEqual(current_user.avatar_url, profile['profile']['avatar'])
self.assertEqual(len(User.objects), 1)
def test_trigger_oauth_login_on_cookie(self):
'''Should trigger a OAuth handshake if YouCKAN cookie is present'''
with self.app.test_client() as client:
self.assertFalse(current_user.is_authenticated)
client.set_cookie('udata.dev', YouckanSettings.YOUCKAN_SESSION_COOKIE, 'session_id')
client.set_cookie('udata.dev', YouckanSettings.YOUCKAN_AUTH_COOKIE, 'whatever')
client.set_cookie('udata.dev', YouckanSettings.YOUCKAN_AUTH_COOKIE + '.logged', 'whatever')
response = self.get('/somewhere', client=client)
self.assertStatus(response, 302)
response_url = urlparse(response.location)
expected_url = urlparse(self.app.config['YOUCKAN_AUTHORIZE_URL'])
self.assertEqual(response_url.hostname, expected_url.hostname)
self.assertEqual(response_url.path, expected_url.path)
qs = parse_qs(response_url.query)
self.assertIn('state', qs)
state = decode_state(qs['state'][0])
self.assertEqual(state['next_url'], 'https://localhost/somewhere')
@httpretty.activate
def test_oauth_authorization_should_preserve_current_page(self):
'''OAuth handshake should preserve current viewed page'''
user = UserFactory()
next_url = '/somewhere'
state = encode_state(url=next_url)
with self.mock_authorize(slug=user.slug) as (profile, client):
response = self.get(url_for('youckan.authorized', code='code', state=state), client=client)
self.assertRedirects(response, next_url)
def test_force_logout_if_cookie_is_missing(self):
'''Should silently disconnect user if YouCKAN cookie is missing'''
with self.app.test_client() as client:
self.login(client=client)
response = self.get(url_for('site.dashboard'), base_url='https://localhost', client=client)
self.assert200(response)
self.assertFalse(current_user.is_authenticated)