-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_middleware.py
482 lines (363 loc) · 16.6 KB
/
test_middleware.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# encoding: utf-8
import wsgiref
import flask
import mock
import pytest
from flask import Blueprint
import ckan.lib.helpers as h
import ckan.model as model
import ckan.plugins as p
import ckan.tests.factories as factories
from ckan.common import config, _
from ckan.config.middleware import AskAppDispatcherMiddleware
from ckan.config.middleware.flask_app import CKANFlask
from ckan.config.middleware.pylons_app import CKANPylonsApp
_test_controller = u'ckan.tests.config.test_middleware:MockPylonsController'
class MockRoutingPlugin(p.SingletonPlugin):
p.implements(p.IRoutes)
p.implements(p.IBlueprint)
controller = _test_controller
def before_map(self, _map):
_map.connect(u'/from_pylons_extension_before_map',
controller=self.controller,
action=u'view')
_map.connect(u'/from_pylons_extension_before_map_post_only',
controller=self.controller,
action=u'view',
conditions={u'method': u'POST'})
# This one conflicts with an extension Flask route
_map.connect(u'/pylons_and_flask',
controller=self.controller,
action=u'view')
# This one conflicts with a core Flask route
_map.connect(u'/about', controller=self.controller, action=u'view')
_map.connect(u'/pylons_route_flask_url_for',
controller=self.controller,
action=u'test_flask_url_for')
_map.connect(u'/pylons_translated',
controller=self.controller,
action=u'test_translation')
return _map
def after_map(self, _map):
_map.connect(u'/from_pylons_extension_after_map',
controller=self.controller,
action=u'view')
return _map
def get_blueprint(self):
# Create Blueprint for plugin
blueprint = Blueprint(self.name, self.__module__)
blueprint.add_url_rule(u'/simple_flask', u'flask_plugin_view',
flask_plugin_view)
blueprint.add_url_rule(u'/flask_route_pylons_url_for',
u'flask_route_pylons_url_for',
flask_plugin_view_url_for)
blueprint.add_url_rule(u'/flask_translated', u'flask_translated',
flask_translated_view)
return blueprint
def flask_plugin_view():
return u'Hello World, this is served from a Flask extension'
def flask_plugin_view_url_for():
url = h.url_for(controller=_test_controller, action=u'view')
return u'This URL was generated by Pylons: {0}'.format(url)
def flask_translated_view():
return _(u'Dataset')
class MockPylonsController(p.toolkit.BaseController):
def view(self):
return u'Hello World, this is served from a Pylons extension'
def test_flask_url_for(self):
url = h.url_for(u'api.get_api', ver=3)
return u'This URL was generated by Flask: {0}'.format(url)
def test_translation(self):
return _(u'Groups')
@pytest.mark.ckan_pytest
class TestAppDispatcher:
@pytest.fixture
def app(cls, app):
flask_app = app.flask_app
def test_view():
return u'This was served from Flask'
# This endpoint is defined both in Flask and in Pylons core
flask_app.add_url_rule(u'/flask_core',
view_func=test_view,
endpoint=u'flask_core.index')
# This endpoint is defined both in Flask and a Pylons extension
flask_app.add_url_rule(u'/pylons_and_flask',
view_func=test_view,
endpoint=u'pylons_and_flask.index')
return app
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_ask_around_flask_core_and_pylons_extension_route(self, app):
environ = {
u'PATH_INFO': u'/pylons_and_flask',
u'REQUEST_METHOD': u'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
answers = sorted(answers, key=lambda a: a[1])
assert answers == [(True, u'flask_app', u'core'),
(True, u'pylons_app', u'extension')]
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_flask_core_and_pylons_extension_route_is_served_by_pylons(
self, app):
res = app.get(u'/pylons_and_flask')
assert res.environ[u'ckan.app'] == u'pylons_app'
assert res.body == u'Hello World, this is served from a Pylons extension'
def test_ask_around_pylons_core_route_get(self, app):
environ = {
u'PATH_INFO': u'/tag',
u'REQUEST_METHOD': u'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'core')]
def test_ask_around_pylons_core_route_post(self, app):
environ = {
u'PATH_INFO': u'/tag',
u'REQUEST_METHOD': u'POST',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'core')]
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_ask_around_pylons_extension_route_get_before_map(self, app):
environ = {
u'PATH_INFO': u'/from_pylons_extension_before_map',
u'REQUEST_METHOD': u'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'extension')]
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_ask_around_pylons_extension_route_post(self, app):
environ = {
u'PATH_INFO': u'/from_pylons_extension_before_map_post_only',
u'REQUEST_METHOD': u'POST',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'extension')]
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_ask_around_pylons_extension_route_post_using_get(self, app):
environ = {
u'PATH_INFO': u'/from_pylons_extension_before_map_post_only',
u'REQUEST_METHOD': u'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
# We are going to get an answer from Pylons, but just because it will
# match the catch-all template route, hence the `core` origin.
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'core')]
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_ask_around_pylons_extension_route_get_after_map(self, app):
environ = {
u'PATH_INFO': u'/from_pylons_extension_after_map',
u'REQUEST_METHOD': u'GET',
}
wsgiref.util.setup_testing_defaults(environ)
answers = app.app.ask_around(environ)
assert answers == [(False, u'flask_app'),
(True, u'pylons_app', u'extension')]
def test_flask_core_route_is_served_by_flask(self, app):
res = app.get(u'/')
assert res.environ[u'ckan.app'] == u'flask_app'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_flask_extension_route_is_served_by_flask(self, app):
res = app.get(u'/simple_flask')
assert res.environ[u'ckan.app'] == u'flask_app'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_pylons_extension_route_is_served_by_pylons(self, app):
res = app.get(u'/from_pylons_extension_before_map')
assert res.environ[u'ckan.app'] == u'pylons_app'
assert res.body == u'Hello World, this is served from a Pylons extension'
def test_flask_core_and_pylons_core_route_is_served_by_flask(self, app):
'''
This should never happen in core, but just in case
'''
res = app.get(u'/flask_core')
assert res.environ[u'ckan.app'] == u'flask_app'
assert res.body == u'This was served from Flask'
@pytest.mark.ckan_pytest
@pytest.mark.usefixtures(u'reset_all')
class TestFlaskUserIdentifiedInRequest:
'''Flask identifies user during each request.
Flask route provided by test.helpers.SimpleFlaskPlugin.
'''
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_g_normal_user(self, app):
'''
A normal logged in user request will have expected user objects added
to request.
'''
user = factories.User()
test_user_obj = model.User.by_name(user[u'name'])
with app.flask_app.app_context():
app.get(
u'/simple_flask',
extra_environ={u'REMOTE_USER': user[u'name'].encode(u'ascii')},
)
assert flask.g.user == user[u'name']
assert flask.g.userobj == test_user_obj
assert flask.g.author == user[u'name']
assert flask.g.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_g_anon_user(self, app):
'''
An anon user request will have expected user objects added to request.
'''
with app.flask_app.app_context():
app.get(
u'/simple_flask',
extra_environ={u'REMOTE_USER': str(u'')},
)
assert flask.g.user == u''
assert flask.g.userobj is None
assert flask.g.author == u'Unknown IP Address'
assert flask.g.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_g_sysadmin(self, app):
'''
A sysadmin user request will have expected user objects added to
request.
'''
user = factories.Sysadmin()
test_user_obj = model.User.by_name(user[u'name'])
with app.flask_app.app_context():
app.get(
u'/simple_flask',
extra_environ={u'REMOTE_USER': user[u'name'].encode(u'ascii')},
)
assert flask.g.user == user[u'name']
assert flask.g.userobj == test_user_obj
assert flask.g.author == user[u'name']
assert flask.g.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_pytest
class TestPylonsUserIdentifiedInRequest:
'''Pylons identifies user during each request.
Using a route setup via an extension to ensure we're always testing a
Pylons-flavoured request.
'''
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_c_normal_user(self, app):
'''
A normal logged in user request will have expected user objects added
to request.
'''
user = factories.User()
test_user_obj = model.User.by_name(user[u'name'])
resp = app.get(
u'/from_pylons_extension_before_map',
extra_environ={u'REMOTE_USER': user[u'name'].encode(u'ascii')})
# tmpl_context available on response
assert resp.tmpl_context.user == user[u'name']
assert resp.tmpl_context.userobj == test_user_obj
assert resp.tmpl_context.author == user[u'name']
assert resp.tmpl_context.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_c_anon_user(self, app):
'''An anon user request will have expected user objects added to
request.
'''
resp = app.get(u'/from_pylons_extension_before_map',
extra_environ={u'REMOTE_USER': str(u'')})
# tmpl_context available on response
assert resp.tmpl_context.user == u''
assert resp.tmpl_context.userobj is None
assert resp.tmpl_context.author == u'Unknown IP Address'
assert resp.tmpl_context.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
def test_user_objects_in_c_sysadmin(self, app):
'''A sysadmin user request will have expected user objects added to
request.
'''
user = factories.Sysadmin()
test_user_obj = model.User.by_name(user[u'name'])
resp = app.get(
u'/from_pylons_extension_before_map',
extra_environ={u'REMOTE_USER': user[u'name'].encode(u'ascii')})
# tmpl_context available on response
assert resp.tmpl_context.user == user[u'name']
assert resp.tmpl_context.userobj == test_user_obj
assert resp.tmpl_context.author == user[u'name']
assert resp.tmpl_context.remote_addr == u'Unknown IP Address'
@pytest.mark.ckan_pytest
@pytest.mark.ckan_config(u'SECRET_KEY', u'super_secret_stuff')
def test_secret_key_is_used_if_present(app):
assert app.flask_app.config[u'SECRET_KEY'] == u'super_secret_stuff'
@pytest.mark.ckan_pytest
@pytest.mark.ckan_config(u'SECRET_KEY', None)
def test_beaker_secret_is_used_by_default(app):
assert app.flask_app.config[u'SECRET_KEY'] == config[
u'beaker.session.secret']
@pytest.mark.ckan_pytest
@pytest.mark.ckan_config(u'SECRET_KEY', None)
@pytest.mark.ckan_config(u'beaker.session.secret', None)
def test_no_beaker_secret_crashes(make_app):
# TODO: When Pylons is finally removed, we should test for
# RuntimeError instead (thrown on `make_flask_stack`)
with pytest.raises(ValueError,
match=ur"'secret' or 'secretfile' must not be None"):
make_app()
@pytest.mark.ckan_pytest
@pytest.mark.ckan_config(u'ckan.plugins', u'test_routing_plugin')
@pytest.mark.ckan_config(u'ckan.use_pylons_response_cleanup_middleware', True)
def test_pylons_route_with_cleanup_middleware_activated(app):
u'''Test the home page renders with the middleware activated
We are just testing the home page renders without any troubles and that
the middleware has not done anything strange to the response string'''
response = app.get(url=u'/pylons_translated')
assert 200 == response.status_int
# make sure we haven't overwritten the response too early.
assert (u'cleanup middleware' not in response.body)
@pytest.mark.ckan_pytest
@pytest.mark.parametrize(u'rv,app_base',
[((False, u'flask_app'), CKANFlask),
((True, u'pylons_app', u'core'), CKANPylonsApp)])
def test_can_handle_request_with_environ(monkeypatch, app, rv, app_base):
ckan_app = app.app
handler = mock.Mock(return_value=rv)
monkeypatch.setattr(app_base, u'can_handle_request', handler)
environ = {u'PATH_INFO': str(u'/')}
wsgiref.util.setup_testing_defaults(environ)
start_response = mock.MagicMock()
ckan_app(environ, start_response)
assert handler.called_with(environ)
@pytest.mark.ckan_pytest
def test_ask_around_is_called(monkeypatch, app):
ask = mock.MagicMock()
monkeypatch.setattr(AskAppDispatcherMiddleware, u'ask_around', ask)
app.get(u'/', status=404)
assert ask.called
@pytest.mark.ckan_pytest
def test_ask_around_is_called_with_args(monkeypatch, app):
ckan_app = app.app
environ = {}
start_response = mock.MagicMock()
wsgiref.util.setup_testing_defaults(environ)
ask = mock.MagicMock()
monkeypatch.setattr(AskAppDispatcherMiddleware, u'ask_around', ask)
ckan_app(environ, start_response)
assert ask.called
ask.assert_called_with(environ)
@pytest.mark.ckan_pytest
def test_ask_around_flask_core_route_get(app):
ckan_app = app.app
environ = {u'PATH_INFO': u'/', u'REQUEST_METHOD': u'GET'}
wsgiref.util.setup_testing_defaults(environ)
answers = ckan_app.ask_around(environ)
assert answers == [(True, u'flask_app', u'core'), (False, u'pylons_app')]
@pytest.mark.ckan_pytest
def test_ask_around_flask_core_route_post(app):
ckan_app = app.app
environ = {u'PATH_INFO': u'/group/new', u'REQUEST_METHOD': u'POST'}
wsgiref.util.setup_testing_defaults(environ)
answers = ckan_app.ask_around(environ)
# Even though this route is defined in Flask, there is catch all route
# in Pylons for all requests to point arbitrary urls to templates with
# the same name, so we get two positive answers
assert answers == [(True, u'flask_app', u'core'),
(True, u'pylons_app', u'core')]